C++ While Loop
Loops repeat a block of code. The while loop is the simplest one: it keeps running as long as its condition is true. Use it when you do not know in advance how many repetitions you need.
The while loop
#include <iostream>
using namespace std;
int main() {
int countdown = 5;
while (countdown > 0) {
cout << countdown << "... ";
countdown--;
}
cout << "Liftoff!\n";
}5... 4... 3... 2... 1... Liftoff!
Before each pass ("iteration") the condition is checked. When countdown reaches 0, the condition is false and the loop ends. If the condition is false from the start, the body never runs.
Warning: Something in the body must eventually make the condition false. If you forget
countdown--, the loop runs forever — an infinite loop.
Looping until something happens
while shines when the number of steps depends on the data. How many years until savings double at 7% interest?
#include <iostream>
using namespace std;
int main() {
double balance = 1000.0;
int years = 0;
while (balance < 2000.0) {
balance *= 1.07;
years++;
}
cout << "Doubled after " << years << " years\n";
}Doubled after 11 years
Another classic: the Collatz sequence. Halve even numbers, turn odd ones into 3n + 1, and stop at 1:
#include <iostream>
using namespace std;
int main() {
int n = 6;
int steps = 0;
while (n != 1) {
cout << n << " ";
n = (n % 2 == 0) ? n / 2 : 3 * n + 1;
steps++;
}
cout << n << "\n" << steps << " steps\n";
}6 3 10 5 16 8 4 2 1
8 steps
The do..while loop
A do..while loop checks its condition after the body, so the body always runs at least once. It is the natural fit for menus and "ask again until valid" input:
#include <iostream>
using namespace std;
int main() {
int number = 100;
do {
cout << "number = " << number << "\n";
number++;
} while (number < 100);
}number = 100
Even though number < 100 is false from the start, the body ran once. Note the semicolon after while (...) — it is required here.
A typical use with real input looks like this (not runnable here because it reads from the keyboard):
int choice;
do {
cout << "1) Play 2) Settings 0) Quit\n> ";
cin >> choice;
} while (choice != 0);while vs do..while
while |
do..while |
|
|---|---|---|
| Condition checked | before each iteration | after each iteration |
| Minimum runs | 0 | 1 |
| Typical use | processing until a condition changes | menus, input validation |
Test yourself
How many times does the body of while (false) { ... } run?
- 0
- 1
- Forever
- It does not compile
What is the minimum number of times a do..while body runs?
- 0
- 1
- 2
- Depends on the compiler
What is printed? int i = 0; while (i < 3) { i++; } cout << i;
- 2
- 3
- 4
- 0