Basic

Loops and Iteration

Repeat work with for, while, and enhanced for loops.

What you will see

0 1 2 3 4

About 2 min of reading

Try It

Repeat work with three loop styles. Count with for, count down with while, and walk over an array with the enhanced for, then stop early with break.

1

Count up with a for loop. The three parts, initialize, check, update, are all on one line. The body runs while the condition stays true.

class Main { public static void main(String[] args) { for (int i = 0; i < 3; i++) { System.out.println(i); } } }

Before you run it, say out loud what it will print. Then open the answer.

What it prints
0 1 2
The loop stops before the condition becomes false. i < 3 prints 0, 1, 2 but never 3.
2

Count down with a while loop. The condition is checked first, so the body only runs while it is true. Decrement the counter inside or the loop never ends.

class Main { public static void main(String[] args) { int n = 3; while (n > 0) { System.out.println(n); n--; } } }

Before you run it, say out loud what it will print. Then open the answer.

What it prints
3 2 1
Forget to decrement n and the loop runs forever. A while loop with no exit ever reached is the classic infinite loop.
3

Walk over an array with the enhanced for (for-each). You do not touch the index at all, you just get each value in order.

class Main { public static void main(String[] args) { String[] names = {"Ada", "Bob", "Cy"}; for (String name : names) { System.out.println(name); } } }

Before you run it, say out loud what it will print. Then open the answer.

What it prints
Ada Bob Cy
The enhanced for is perfect for reading values, but it cannot change the array's length or reach elements by index.
4

Exit a loop early with break. The loop prints until the counter hits 5, then stops, the break skips everything after it.

class Main { public static void main(String[] args) { for (int i = 0; i < 10; i++) { if (i == 5) break; System.out.println(i); } } }

Before you run it, say out loud what it will print. Then open the answer.

What it prints
0 1 2 3 4
break jumps out of the loop entirely. If you wanted to skip just one value instead, use continue.

Put it in order

Before you write anything, put these lines back in the right order. Click a line to move it up one step. This support step is easier than writing code from scratch, and it is here to make the last example stick.

Data Flow

A loop repeats its body: the condition is checked, the body runs, and the update runs before the next check.
1 Initialize loop counter
↓
2 Check condition -> true continues
↓
3 Execute body
↓
4 Update counter, repeat
Why this works
break and continue

break exits the loop entirely; continue skips to the next iteration:

for (int i = 0; i < 10; i++) {
    if (i == 5) break;       // stop at 5
    if (i % 2 == 0) continue; // skip evens
    System.out.println(i);
}

Use break to stop early on a match; use continue to skip unwanted iterations without leaving the loop.

Nested loops and complexity

A loop inside a loop multiplies iterations:

for (int i = 0; i < 3; i++) {
    for (int j = 0; j < 3; j++) {
        System.out.println(i + "," + j);
    }
}

This is O(n²), 9 iterations for n=3. Nested loops are powerful but expensive; avoid nesting more than two levels deep in performance-critical code.

Examples

Standard for loop

Counting with a for loop

for (int i = 0; i < 5; i++) {
    System.out.println(i);   // 0 1 2 3 4
}

The for loop has three parts: initialization, condition, and update. It runs while the condition is true.

While and do-while

Looping until a condition

int n = 3;
while (n > 0) {
    System.out.println(n);
    n--;
}

dow {
    System.out.println("Still going");
} while (false);   // runs once, condition checked after

while checks the condition before running. do-while always runs the body at least once.

Enhanced for loop

Iterating collections

String[] names = {"Ada", "Bob", "Cy"};
for (String name : names) {
    System.out.println(name);
}

The enhanced for loop (for-each) simplifies iterating arrays and collections. It cannot modify the array length but can change element values.

Words this lesson uses

Each one is defined here on this site. Open the entry for the full definition and the other words it points at.

← Control Flow: Conditionals
Previous Lesson
Control Flow: Conditionals
Next Lesson
Arrays and Lists
Arrays and Lists →