Skip to content

Beginner · Control flow and methods · topic 8 of 60 · 25 min

Loops: for, while, do-while and for-each

Explanation

for loops count, while loops repeat until a condition is false, do-while runs at least once, and the enhanced for (for-each) walks through every element of an array or collection. break leaves a loop, continue skips to the next round, and a label lets break leave an outer loop.

The for loop

java
for (int i = 1; i <= 5; i++) {
    System.out.println("7 x " + i + " = " + (7 * i));
}
Start; condition checked before each round; update after each round.

while and do-while

java
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);         // 1

Enhanced for (for-each)

java
String[] cities = {"Delhi", "Mumbai", "Chennai"};
for (String city : cities) {
    System.out.println(city.toUpperCase());
}
Use for-each when you need every element and not the index.

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

java
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.
java
for (int i = 1; i <= 4; i++) {
    System.out.println("*".repeat(i));    // String.repeat: Java 11+
}
Prints a star triangle: *, **, ***, ****.
Careful: Off-by-one errors: for (int i = 0; i <= arr.length; i++) reads arr[arr.length], which throws ArrayIndexOutOfBoundsException. Use i < arr.length. And make sure while loops change the variable they test, or they never end.
Think of it like this: A for loop is like a teacher calling roll numbers 1 to 40: you know exactly how many. A while loop is like filling a bucket from a slow tap: you keep going until it is full, however long that takes.
Tip: Pick the loop by the question: "for each item" → for-each; "count from a to b" → for; "until something happens" → while; "at least once, then maybe again" → do-while (for example a menu).

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

Loops

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.

java
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));
}
Prints 6 lines; the loan is cleared in month 6.

Practice (0/3 done)

Task 1 · Question

What does this print? int s = 0; for (int i = 1; i <= 10; i += 3) s += i; System.out.println(s);

Task 2 · Question

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);

Task 3 · Code · Javascript

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

Question 1

1.Which loop is guaranteed to run its body at least once?

Question 2

2.for (int i = 0; i < 5; i++) — what is the last value of i inside the loop?

Question 3

3.What does continue do?

Question 4

4.How do you leave an outer loop from inside an inner loop?

Read more (free)

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.

From Loops: for, while, do…while, for…of and for…in

Which loop always runs its body at least once?Related

Answer: do-while

do-while checks its condition after the body.

From Loops: for, while, do-while and range-for

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.

From Loops: repeating work

Which loop always runs its body at least once?Related

Answer: do-while

do-while checks the condition after the body.

From Loops: for, while, do-while and foreach

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

  1. 2 more topics in “Control flow and methods” before its exam: Methods: parameters, return values and overloading, Reading errors and debugging.
  2. Module 2 exam: Control flow and methods · 12 questions · 25 min, without help. 5 topics of this module still to finish first.
  3. Then the next module, Arrays and strings. 60 topics left in the course before the final exam.

← Previous: switch statements and switch expressions