Lesson 8 · 8 of 20
while and do-while · C++
Repeat code in C++ with while as long as a condition holds, with do-while at least once, and steer the loop with break and continue.

`while` repeats a block as long as the condition is true. Saving 120 euros a month, the loop goes round until savings reaches 500: after 5 months there are 600. Something inside the loop must eventually change the condition, or it would never end.
The countdown fits on one line: seconds-- uses the current value for printing and then subtracts one. When it hits 0 the condition fails and the program moves on to Lift off!.
`do { ... } while (condition);` checks the condition at the end, so the block runs at least once: the player gets a turn even though energy is 0. Note the semicolon after the while.
`while (true)` would loop forever, but `break` ends it as soon as n goes past 10. `continue` jumps straight to the next round without printing anything, which is how 3, 6 and 9 are skipped.
Code · main.cpp
#include <iostream>int main() { // while repeats the block as long as the condition is true. int savings = 0, months = 0; while (savings < 500) { savings += 120; months++; } std::cout << "Goal reached in " << months << " months: " << savings << " euros\n"; // A countdown: seconds-- uses the value, then subtracts one. int seconds = 5; while (seconds > 0) std::cout << seconds-- << "... "; std::cout << "Lift off!\n"; // do-while runs the block once before checking the condition. int energy = 0; do { std::cout << "The player gets one turn (energy " << energy << ")\n"; } while (energy > 0); // break leaves the loop; continue jumps to the next round. int n = 0; while (true) { n++; if (n % 3 == 0) continue; // skip multiples of 3 if (n > 10) break; std::cout << n << ' '; } std::cout << '\n'; return 0;}Output · c++ -std=c++17 main.cpp -o main && ./main
Goal reached in 5 months: 600 euros 5... 4... 3... 2... 1... Lift off! The player gets one turn (energy 0) 1 2 4 5 7 8 10
Key points
whilechecks the condition before each round.do-whilechecks it afterwards: it runs at least once.- Something inside the loop must change the condition.
breakleaves the loop;continuemoves on to the next round.
Exercise
A plant is 5 cm tall and grows 20% every week. Use a while to work out how many weeks it takes to pass 30 cm, printing its height each week.