5.1 — while loops
Read one box at a time. No rush.
Repeat while true#
A while loop repeats its code as long as the condition is true.
C++
int count { 1 }; while (count <= 5){ std::cout << count << ' '; ++count;}Output
1 2 3 4 5How it works#
- Check the condition. Is
count <= 5? - If true: run the code inside
{ }, then go back to step 1. - If false: skip the loop and carry on below it.
Each trip through the loop is called an iteration.
Infinite loops#
If the condition never becomes false, the loop never ends.
C++ — wrong ✗
int count { 1 };while (count <= 5){ std::cout << count; // forgot ++count! count is always 1}Watch out
Make sure something inside the loop moves it toward the end. If your program freezes, press Ctrl + C in the terminal to stop it.
Looping until the user is done#
C++
int number {};std::cout << "Enter numbers to add (0 to stop):\n"; int total { 0 };std::cin >> number;while (number != 0){ total += number; std::cin >> number;}std::cout << "Total: " << total << '\n';Tip: press ← / → to move between lessons, / to search.