Skip to content
KALANBLON
Show contents

Chapter 4 of 6 · 20 min

The while and for loops

By the end of this chapter, you'll be able to

  • Repeat while a condition is true with while
  • Run at least once with do while
  • Count with a for loop and choose its bounds
  • Control a loop with break and continue

while: as long as…

void main() {
    double debt = 1000;
    final double MONTHLY_PAYMENT = 150;
    int months = 0;
    while (debt > 0) {
        debt = debt * 1.01 - MONTHLY_PAYMENT;   // 1% interest a month
        months++;
    }
    IO.println("Paid back in " + months + " months");
}
Paid back in 7 months

The condition is tested before each round: as long as it's true, the block runs. If it's false from the start, the block never runs.

do { … } while (condition); tests the condition after the block, which therefore runs at least once. Handy for asking again for input until it's valid. Don't forget the final ;.

for: counting

i no longer exists after the loop. We display 20.

Step 9 of 9
Text description of the animation
  1. We add up 2, 4, 6 and 8.
  2. sum starts at 0.
  3. The initialisation creates i = 2, only once. The condition is true.
  4. First round: sum is 2.
  5. i += 2 moved i to 4: sum is 6.
  6. With i = 6: sum is 12.
  7. With i = 8: sum is 20.
  8. i becomes 10: the condition is false, the loop stops.
  9. i no longer exists after the loop. We display 20.

The for loop brings together the initialisation (run once), the condition (tested before each round) and the update (run at the end of each round).

  • break leaves the loop immediately;
  • continue moves on to the next round.
void main() {
    // 9 times table, skipping the odd results
    for (int i = 1; i <= 6; i++) {
        int r = 9 * i;
        if (r % 2 != 0) {
            continue;
        }
        IO.println("9 x " + i + " = " + r);
    }
    // First square greater than 500
    int n = 1;
    while (true) {
        if (n * n > 500) {
            break;
        }
        n++;
    }
    IO.println(n + "² = " + n * n);
}
9 x 2 = 18
9 x 4 = 36
9 x 6 = 54
23² = 529

while (true) creates an endless loop, which you can only leave with break. It's useful when the exit condition is computed in the middle of the block, but make sure a break will always be reached.

Your turn

Worked exercise

Worked exercise: the Collatz sequence

Start from an integer n. If it's even, divide it by 2; otherwise, multiply it by 3 and add 1. Repeat until you get 1. Write a program that displays all the values starting from n = 6, then the number of steps: 6 3 10 5 16 8 4 2 1 and 8 steps.

Hint 1
A while (n != 1) loop fits: you don't know in advance how many steps it will take.
Hint 2
Display n with IO.print(n + " ") before transforming it, then display the final 1 after the loop.
Show the solution and common mistakes
void main() {
    int n = 6;
    int steps = 0;
    while (n != 1) {
        IO.print(n + " ");
        n = (n % 2 == 0) ? n / 2 : 3 * n + 1;
        steps++;
    }
    IO.println(n);
    IO.println(steps + " steps");
}
6 3 10 5 16 8 4 2 1
8 steps

Nobody has yet proved that this sequence reaches 1 for every starting integer: it's an open mathematical problem, the Collatz conjecture.

Common mistakes:

  • Starting from n = 0: 0 is even and 0 / 2 is 0, so the loop never stops. Check that the starting value is a strictly positive integer.
  • Counting the steps before the loop, or forgetting to display the final 1.

Summary

  1. 1while tests before each round; do { … } while (…); runs at least once.
  2. 2for (init; condition; update) is ideal for counting.
  3. 3break leaves the loop, continue moves on to the next round.
  4. 4Check the first and the last value of the counter to avoid one round too many or too few.
  5. 5Each loop must bring its condition closer to the exit.

Your progress is saved on this device. Create a free account to keep your progress on all your devices.