Skip to main content

Lesson 4 of 5 15 min read

Loops and iteration

Repeat work with for, while and do-while loops, loop over arrays, and avoid off-by-one and infinite loops.

In this lesson you will

  • Write for, while and do-while loops and explain when to use each
  • Iterate over an array with an index and with the enhanced for loop
  • Use break and continue, and recognise off-by-one and infinite loops

Why loops?

Imagine printing the numbers 1 to 100. Writing 100 print statements is slow and error-prone. A loop repeats a block of code while a condition stays true.

The for loop

Use for when you know how many times to repeat:

Java
for (int i = 1; i <= 5; i++) {
    System.out.println("Step " + i);
}

The header has three parts separated by semicolons:

  1. Initialisation int i = 1 runs once, before the loop starts.
  2. Condition i <= 5 is checked before every repetition (an iteration). When it is false, the loop ends.
  3. Update i++ runs after each iteration.

This prints Step 1 to Step 5.

After int i = 1 runs once, these steps repeat until the check is false

A repeating cycle: Check i <= 5, then Run the body, then Update i++, then back to Check i <= 5

The while loop

Use while when you don't know in advance how many repetitions you need:

Java
int balance = 1000;
int months = 0;
while (balance < 2000) {
    balance = balance + balance * 10 / 100; // grows 10% each month
    months++;
}
System.out.println("Months needed: " + months); // Months needed: 8

The do-while loop

A do-while loop checks its condition after the body, so the body always runs at least once. It suits menus and input prompts:

Java
int attempts = 0;
do {
    attempts++;
    System.out.println("Attempt " + attempts);
} while (attempts < 3);

Looping over arrays

An array stores several values of the same type. Indexes start at 0.

Java
int[] marks = {78, 92, 65, 88};

int sum = 0;
for (int i = 0; i < marks.length; i++) {
    sum += marks[i];
}
System.out.println("Average: " + (double) sum / marks.length); // Average: 80.75

// Enhanced for loop: read each value without managing an index
for (int m : marks) {
    if (m > 80) {
        System.out.println(m + " is a distinction");
    }
}

(double) sum converts the total to a double so the division keeps its decimal part.

break and continue

  • break exits the loop immediately.
  • continue skips the rest of the current iteration and moves to the next one.
Java
for (int n = 1; n <= 10; n++) {
    if (n % 2 == 0) continue;  // skip even numbers
    if (n > 7) break;          // stop after 7
    System.out.println(n);     // prints 1, 3, 5, 7
}

Common mistakes

  • Off-by-one errors: with an array of length 4, the valid indexes are 0 to 3. Writing i <= marks.length tries to read marks[4] and throws an ArrayIndexOutOfBoundsException.
  • Infinite loops: if the condition never becomes false, the loop never ends. In while (count < 10), forgetting count++ keeps count at its starting value forever.

Hands-on exercise

Write a program that prints the multiplication table of 7 from 7 × 1 to 7 × 10. Then, given int[] prices = {120, 450, 80, 999, 300}, use a loop to find and print the highest price without using any library method.

Knowledge check

3 questions • 70% to pass • Practice only, no certificate

  1. 1.What is printed?
    CODE
    int total = 0;
    for (int i = 1; i <= 4; i++) {
        total += i;
    }
    System.out.println(total);
  2. 2.An array has 5 elements. Which index refers to the last one?
  3. 3.What does continue do inside a loop?
0 of 3 answered

Key concepts

  • for suits a known number of repetitions; while suits repeating until something changes.
  • do-while always runs its body at least once because the condition is checked afterwards.
  • Array indexes run from 0 to length - 1; the enhanced for loop reads each element in turn.
  • break leaves a loop, continue skips to the next iteration, and every loop needs a way to stop.