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…

#include <iostream>

int main() {
    int population = 1000;
    int years = 0;
    while (population < 2000) {
        population = population * 112 / 100;   // +12% a year
        years++;
    }
    std::cout << "Population doubled in " << years << " years (" << population << ")\n";
    return 0;
}
Population doubled in 7 years (2207)

The condition is tested before each round. If it's true, the block runs, then we go back to test it. As soon as it's false, the program carries on after the loop. 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. It's the ideal loop for asking again for input as long as it's incorrect. Don't forget the final ;.

for: counting

When you know how many rounds to make, for gathers everything on one line: the initialisation, the condition and the increment.

i no longer exists outside the loop. We display 24.

Step 9 of 9
Text description of the animation
  1. We compute 4! = 1 × 2 × 3 × 4.
  2. fact starts at 1, the neutral element of multiplication.
  3. The initialisation creates i = 1, only once. The condition is true.
  4. fact *= 1: fact stays at 1.
  5. i++ moved i to 2, the condition is still true: fact is 2.
  6. Next round with i = 3: fact is 6.
  7. With i = 4: fact is 24.
  8. i becomes 5: the condition is false, the loop stops.
  9. i no longer exists outside the loop. We display 24.
  • break leaves the loop immediately;
  • continue moves on to the next round, skipping the end of the block.
#include <iostream>

int main() {
    for (int i = 1; i <= 15; i++) {
        if (i % 15 == 0) {
            std::cout << "FizzBuzz\n";
        } else if (i % 3 == 0) {
            std::cout << "Fizz ";
        } else if (i % 5 == 0) {
            std::cout << "Buzz ";
        } else {
            std::cout << i << " ";
        }
    }
    for (int code = 1000; code < 10000; code++) {
        if (code % 7 == 0 && code % 13 == 0 && code % 11 == 0) {
            std::cout << "First code divisible by 7, 11 and 13: " << code << "\n";
            break;
        }
    }
    return 0;
}
1 2 Fizz 4 Buzz Fizz 7 8 Fizz Buzz 11 Fizz 13 14 FizzBuzz
First code divisible by 7, 11 and 13: 1001

Your turn

Worked exercise

Worked exercise: the mystery number game

The mystery number is 37. The program reads guesses from the keyboard and answers "Higher" or "Lower", until the player finds it. It then displays the number of tries. If there's nothing left to read (end of input), it stops cleanly.

Hint 1
A loop while (std::cin >> guess) reads as long as reading succeeds.
Hint 2
Count the tries on each round, and leave the loop with break when the guess equals the mystery number.
Show the solution and common mistakes
#include <iostream>

int main() {
    const int mystery = 37;
    int guess = 0;
    int tries = 0;
    bool found = false;
    while (std::cin >> guess) {
        tries++;
        if (guess < mystery) {
            std::cout << "Higher\n";
        } else if (guess > mystery) {
            std::cout << "Lower\n";
        } else {
            found = true;
            break;
        }
    }
    if (found) {
        std::cout << "Well done, found in " << tries << " tries!\n";
    }
    return 0;
}
50
25
37
Lower
Higher
Well done, found in 3 tries!

Common mistakes:

  • Only incrementing tries in the "higher" and "lower" branches: the winning guess wouldn't be counted.
  • Writing while (true) without testing the read: if input stops, std::cin fails on every round and the loop never ends.

Summary

  1. 1while (condition) tests before each round; do { … } while (condition); runs at least once.
  2. 2for (init; condition; increment) is ideal for counting: check the first and last value.
  3. 3break leaves the loop, continue moves on to the next round.
  4. 4Each loop must bring its condition closer to the exit, otherwise it's infinite.
  5. 5while (std::cin >> x) reads values as long as reading succeeds.

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