Beginner · Control flow and methods · topic 8 of 60 · 25 min
Loops: for, while, do-while and for-each
Explanation
The for loop
for (int i = 1; i <= 5; i++) {
System.out.println("7 x " + i + " = " + (7 * i));
}while and do-while
int balance = 1000, months = 0;
while (balance > 0) {
balance -= 300;
months++;
}
System.out.println(months); // 4
int tries = 0;
do {
tries++; // runs once even though the condition is false
} while (tries < 0);
System.out.println(tries); // 1Enhanced for (for-each)
String[] cities = {"Delhi", "Mumbai", "Chennai"};
for (String city : cities) {
System.out.println(city.toUpperCase());
}You cannot change an array element through the for-each variable (assigning city = "X" only changes the local variable), and you must not add or remove elements of a collection inside a for-each (that throws ConcurrentModificationException; module 7).
break, continue and labels
for (int n : new int[]{3, 8, -1, 5}) {
if (n < 0) break; // stop the loop
if (n % 2 == 0) continue; // skip even numbers
System.out.println(n); // prints only 3
}
outer:
for (int row = 1; row <= 3; row++) {
for (int seat = 1; seat <= 4; seat++) {
if (row == 2 && seat == 3) {
System.out.println("Found free seat " + row + "-" + seat);
break outer; // leave BOTH loops
}
}
}Loop patterns
- Accumulator: int sum = 0; for (…) sum += x;
- Counter: if (condition) count++;
- Search: boolean found = false; … if (match) { found = true; break; }
- Best so far: int max = arr[0]; for (…) if (x > max) max = x;
- Nested loops: rows and columns, patterns of stars.
for (int i = 1; i <= 4; i++) {
System.out.println("*".repeat(i)); // String.repeat: Java 11+
}Need help?
Stuck on a word or an idea? Search this course, or every course, and jump straight to the explanation or a worked question.
Try:
Watch the lesson
Loops: for, while, do-while and for-each · 1/6
In this lesson you will repeat work with Java loops.
Prefer a video by a teacher? Find free videos on “java loops for while do while for each break continue” on YouTube ↗
In real life: An EMI schedule
A loan app prints a simple repayment schedule. Each month, interest is added on the remaining balance and the EMI is subtracted, until the balance is cleared. The numbers are simplified for learning.
double balance = 50000, monthlyRate = 0.01, emi = 8628;
int month = 0;
while (balance > 0.5) {
month++;
double interest = balance * monthlyRate;
balance = balance + interest - emi;
System.out.printf("Month %d: interest %.2f, balance %.2f%n", month, interest, Math.max(balance, 0));
}Practice (0/3 done)
What does this print? int s = 0; for (int i = 1; i <= 10; i += 3) s += i; System.out.println(s);
How many times does "Hi" print? int i = 10; while (i < 10) { System.out.println("Hi"); i++; } do { System.out.println("Hi"); } while (i < 10);
The same loop logic in JavaScript, which runs here: write emiMonths(principal, monthlyRatePercent, emi) that simulates the loan month by month (add interest on the balance, subtract the EMI) and returns the number of months until the balance is 0 or less. Return -1 if the EMI is not more than the first month's interest (the loan would never end).
Quick quiz
Read more (free)
Related help
Before this, learn
This topic builds on these. If something here feels new, open them first.
Related topics
- Methods: parameters, return values and overloadingControl flow and methods · same module
- Loops: for, while, do…while, for…of and for…inJavaScript Programming (language in depth) · Strings, decisions and loops
- Loops: for, while, do-while and range-forC++ Programming (modern C++ and DSA) · Decisions, loops and functions
- Loops: repeating workFrontend Web Development · JavaScript basics
- Loops: for, while, do-while and foreachC# and .NET · Decisions, loops and methods
- Loops and rangesKotlin and Android App Development · Kotlin basics
Questions people ask about this
Open a question to see the answer and why. The first ones are this topic's own quiz, so try the quiz above before you peek.
Which loop is guaranteed to run its body at least once?
Answer: do-while
do-while checks after the body.
for (int i = 0; i < 5; i++) — what is the last value of i inside the loop?
Answer: 4
The loop stops when i becomes 5.
What does continue do?
Answer: Skips to the next iteration
continue skips the rest of the current iteration.
How do you leave an outer loop from inside an inner loop?
Answer: A labelled break, like break outer;
Labels let break target an outer loop.
Which loop always runs its body at least once?Related
Answer: do…while
do…while checks the condition after the first run.
Which loop always runs its body at least once?Related
Answer: do-while
do-while checks its condition after the body.
Which loop is best to visit every item of an array?Related
Answer: for...of
for...of gives you each item in turn, with no index to manage.
Which loop always runs its body at least once?Related
Answer: do-while
do-while checks the condition after the body.
Pass the quiz (60% or more) or mark this topic as done when you are ready.
Your progress is saved on this device only.
Next steps
- 2 more topics in “Control flow and methods” before its exam: Methods: parameters, return values and overloading, Reading errors and debugging.
- Module 2 exam: Control flow and methods · 12 questions · 25 min, without help. 5 topics of this module still to finish first.
- Then the next module, Arrays and strings. 60 topics left in the course before the final exam.