Iteration (Loops)

IB Syllabus: B2.3.3 — Construct algorithms using pre-condition and post-condition loops, including nested loops.

Table of Contents

  1. Key Concepts
  2. Worked Examples
    1. Example 1: while Loop — Countdown
    2. Example 2: do-while Loop — Input Validation
    3. Example 3: for Loop — Multiplication Table
    4. Example 4: Accumulator Pattern — Running Total
    5. Example 5: Nested Loops — Star Pattern
    6. Example 6: Guessing Game — Combining Patterns
  3. Quick Code Check
  4. Trace Exercise
  5. Trace Exercise 2 — Nested Loop
  6. Code Completion
  7. Spot the Bug
  8. Output Prediction
  9. Practice Exercises
    1. Core
    2. Extension
    3. Challenge
  10. GitHub Classroom
  11. Connections

Key Concepts

Iteration allows a block of code to repeat without writing it multiple times. Java has three loop types — choosing the right one depends on the situation.

Loop type Condition check Best used when
while Before each iteration You repeat while a condition is true; may not run at all
do-while After each iteration The body must execute at least once
for Before each iteration You know exactly how many times to repeat

A pre-condition loop (while, for) checks the condition before running the body — so it may execute zero times. A post-condition loop (do-while) checks after — guaranteeing at least one execution. This is a common IB exam question.


Worked Examples

Example 1: while Loop — Countdown

The while loop checks the condition before each iteration. If the condition is false from the start, the body never runs.

int count = 5;
while (count > 0) {
    System.out.println(count);
    count--;
}
System.out.println("Go!");

Output:

5
4
3
2
1
Go!

How it works:

  • count starts at 5. The condition count > 0 is true, so the body runs.
  • Each iteration prints count and then decrements it.
  • When count reaches 0, the condition is false and the loop ends.

Example 2: do-while Loop — Input Validation

The do-while loop runs the body first, then checks the condition. This guarantees at least one execution — ideal for menus and input validation.

import java.util.Scanner;

Scanner input = new Scanner(System.in);
int number;

do {
    System.out.print("Enter a number between 1 and 10: ");
    number = input.nextInt();
} while (number < 1 || number > 10);

System.out.println("You entered: " + number);

How it works:

  • The prompt runs at least once — the user must enter something before we can check it.
  • If number is outside 1–10, the condition is true and the loop repeats.
  • Once valid input is entered, the condition is false and the loop ends.

The do-while pattern is the natural choice for “ask, then validate” scenarios. A while loop would require duplicating the prompt before and inside the loop.


Example 3: for Loop — Multiplication Table

The for loop combines initialisation, condition, and update in one line — perfect when the number of iterations is known.

int tableNum = 7;
System.out.println("Multiplication table for " + tableNum + ":");

for (int i = 1; i <= 12; i++) {
    System.out.println(tableNum + " x " + i + " = " + (tableNum * i));
}

Output:

Multiplication table for 7:
7 x 1 = 7
7 x 2 = 14
7 x 3 = 21
...
7 x 12 = 84

Structure: for (initialise; condition; update)

  • Initialise: int i = 1 — runs once before the loop starts
  • Condition: i <= 12 — checked before each iteration; loop stops when false
  • Update: i++ — runs after each iteration

Example 4: Accumulator Pattern — Running Total

A common loop pattern: use a variable to accumulate a result across iterations.

import java.util.Scanner;

Scanner input = new Scanner(System.in);
int total = 0;
int count = 0;

System.out.println("Enter numbers to sum (enter -1 to stop):");

int num = input.nextInt();
while (num != -1) {
    total += num;
    count++;
    num = input.nextInt();
}

System.out.println("Sum: " + total);
System.out.println("Numbers entered: " + count);
if (count > 0) {
    System.out.println("Average: " + (double) total / count);
}

Key patterns:

  • Accumulator: total += num — builds up a running sum
  • Counter: count++ — tracks how many values were processed
  • Sentinel value: -1 signals “stop” — the loop runs until the sentinel is entered

The sentinel value (-1 here) is not included in the total. Always read the first value before the loop, then read subsequent values at the end of the loop body.


Example 5: Nested Loops — Star Pattern

Loops can be placed inside other loops. The inner loop completes fully for each iteration of the outer loop.

int rows = 5;
for (int row = 1; row <= rows; row++) {
    for (int col = 1; col <= row; col++) {
        System.out.print("* ");
    }
    System.out.println();
}

Output:

*
* *
* * *
* * * *
* * * * *

How it works:

  • The outer loop controls which row we are on (1 to 5).
  • The inner loop prints stars — the number of stars equals the current row number.
  • System.out.println() after the inner loop moves to the next line.

When tracing nested loops, track both loop variables separately. The inner loop variable resets to its start value for every iteration of the outer loop.


Example 6: Guessing Game — Combining Patterns

This example combines a counter, a boolean flag, and a while loop with two exit conditions.

import java.util.Scanner;

Scanner input = new Scanner(System.in);
int secretNum = 7;
int maxAttempts = 3;
int attempts = 0;
boolean found = false;

while (!found && attempts < maxAttempts) {
    System.out.print("Guess a number (1-10): ");
    int guess = input.nextInt();
    attempts++;

    if (guess == secretNum) {
        System.out.println("Correct! You got it in " + attempts + " attempts.");
        found = true;
    } else if (guess > secretNum) {
        System.out.println("Too high.");
    } else {
        System.out.println("Too low.");
    }
}

if (!found) {
    System.out.println("Out of attempts. The number was " + secretNum + ".");
}

Key patterns:

  • Flag variable: found tracks whether the goal has been reached
  • Compound condition: !found && attempts < maxAttempts — two reasons to stop
  • Counter: attempts limits the number of tries

Quick Code Check

Q1. Which loop is guaranteed to execute its body at least once?

Q2. How many times does the body of for (int i = 0; i < 5; i++) execute?

Q3. What happens if a while loop's condition is false when first evaluated?

Q4. In for (int i = 0; i < 10; i++), when does i++ execute?

Q5. What does this code do?
int count = 5; while (count > 0) { System.out.println(count); }

Q6. How many times does the inner body execute?
for (int row = 1; row <= 3; row++) { for (int col = 1; col <= row; col++) { System.out.print("*"); } }


Trace Exercise

Trace this loop — fill in the values of i and product after each iteration.

int product = 1;
int n = 4;
for (int i = 1; i <= n; i++) {
    product = product * i;
}
Iterationi (at start of body)product after body
1
2
3
4

What is product after the loop ends?

What does this program compute?


Trace Exercise 2 — Nested Loop

Trace the nested loop — fill in the output produced at each step.

for (int i = 1; i <= 3; i++) {
    for (int j = 1; j <= 2; j++) {
        System.out.println(i + "," + j);
    }
}
StepijOutput
1
2
3
4
5
6

How many total lines of output?


Code Completion

This program uses a while loop with a step value of 2 to print all even numbers from 2 to 20. Complete the missing parts to set the correct start value, end condition, and increment.

int num = ;
while (num <= ) {
    System.out.println(num);
    num += ;
}

This program uses the accumulator pattern inside a for loop to calculate the sum of all integers from 1 to n. Complete the missing parts to initialise the accumulator, set the loop start value, and perform the running total update.

int n = 100;
int total = ;
for (int i = ; i <= n; i++) {
    total ;
}
System.out.println("Sum: " + total);

Spot the Bug

This code is supposed to print the numbers 1 to 5 using a while loop, but it contains a common mistake that causes the loop to never terminate. Click the buggy line, then choose the correct fix.

int i = 1;
while (i <= 5) {
    System.out.println(i);
}

What is wrong and how do you fix it?


This code is supposed to calculate the sum of integers from 1 to 10 using a for loop, but the loop variable starts at the wrong value, causing a subtle off-by-one error. Find the bug.

int sum = 0;
for (int i = 0; i <= 10; i++) {
    sum += i;
}
System.out.println("Sum of 1 to 10: " + sum);

What is wrong and how do you fix it?


Output Prediction

This code demonstrates a while loop that counts down from 10 using a non-standard step value of 3. Pay attention to which values of x satisfy the loop condition and when the loop stops.

What does this code print? Type the exact output.

int x = 10;
while (x > 0) {
    System.out.print(x + " ");
    x -= 3;
}
Expected: 10 7 4 1

This code uses nested for loops to print a decreasing-width number pattern. The inner loop’s start value depends on the outer loop variable, so each row begins at a different number. Trace both loop variables carefully.

What does this code print?

for (int i = 1; i <= 4; i++) {
    for (int j = i; j <= 4; j++) {
        System.out.print(j + " ");
    }
    System.out.println();
}
Expected:
1 2 3 4
2 3 4
3 4
4

Practice Exercises

Core

  1. Countdown timer — Write a program that asks the user for a starting number and prints a countdown to 1, then prints “Go!”. Use a while loop.

  2. Sum of range — Use a for loop to calculate and print the sum of all integers from 1 to 100.

  3. Even number printer — Use a for loop to print all even numbers from 2 to 50, separated by spaces.

  4. Input validation — Use a do-while loop to ask the user for a test score (0–100). Keep asking until they enter a valid value, then print the score.

Extension

  1. FizzBuzz — Print numbers from 1 to 30. For multiples of 3, print “Fizz” instead of the number. For multiples of 5, print “Buzz”. For multiples of both, print “FizzBuzz”.

  2. Right triangle — Use nested loops to print a right triangle of * characters with a height entered by the user: ``` *
    • *
      • *

    • ```

  3. Average calculator — Read numbers from the user until they enter -1 (sentinel). Print the count, sum, and average. Handle the case where no numbers are entered.

Challenge

  1. Number pyramid — Use nested loops to print a centred number pyramid:
        1
       2 3
      4 5 6
     7 8 9 10
    
  2. Simple menu system — Create a calculator with a do-while menu loop. Options: (1) Add, (2) Subtract, (3) Multiply, (4) Quit. After each operation, return to the menu until the user quits.

GitHub Classroom

Iteration Exercises
Practice while loops, do-while loops, for loops, and nested loop patterns.

Connections

Prerequisites:

Related Topics:

  • 1D Arrays — loops are essential for array traversal
  • 2D Arrays — nested loops traverse rows and columns

What’s Next:

  • 1D Arrays — the next step in the teaching sequence
  • Algorithms — loops power searching and sorting

Once you are comfortable with loops, 1D arrays become natural — nearly every array operation uses a loop to traverse, search, or modify elements.


Back to top

© EduCS.me — A resource hub for IB Computer Science

This site uses Just the Docs, a documentation theme for Jekyll.