3.1 while and do-while Loops
Loops repeat a block of code. A while loop checks a condition first. As long as the condition holds, C++ runs the loop body, then goes back and checks the condition again.
Basic while structure
A stable while loop usually has three parts:
- Initial value: prepare the loop variable before the loop starts.
- Condition: decide whether the loop should continue.
- Update: change the loop variable inside the loop.
int i = 1; // initial value
while (i <= 5) { // condition
std::cout << "In loop: i = " << i << std::endl;
i++; // update
}
std::cout << "After loop: i = " << i << std::endl;Output:
In loop: i = 1
In loop: i = 2
In loop: i = 3
In loop: i = 4
In loop: i = 5
After loop: i = 6A while loop checks before it runs. That means the loop body may run many times, or it may run zero times. If you forget to update the loop variable, the condition stays true forever and the loop becomes an infinite loop.
Accumulation and averages
Loops often work with an accumulator variable. The program below reads the heights of 5 people and computes the average height.
#include <iostream>
#include <iomanip>
int main() {
int num_people = 5;
double total = 0;
int i = 1;
while (i <= num_people) {
double height;
std::cout << "Enter person " << i << "'s height: ";
std::cin >> height;
total += height;
i++;
}
double average = total / num_people;
std::cout << std::fixed << std::setprecision(2);
std::cout << "Average height: " << average << std::endl;
return 0;
}One possible run:
Enter person 1's height: 160.8
Enter person 2's height: 175.2
Enter person 3's height: 171.2
Enter person 4's height: 181.3
Enter person 5's height: 164
Average height: 170.50total += height adds the current height into the accumulated total. After the loop ends, total stores the sum of all heights.
Looping until a condition changes
while is useful when the number of repetitions is not known immediately. For example, you can count how many digits an integer has.
int num;
std::cin >> num;
if (num < 0) {
num = -num;
}
int digits;
if (num == 0) {
digits = 1;
} else {
digits = 0;
while (num != 0) {
num /= 10;
digits++;
}
}
std::cout << "Digits: " << digits << std::endl;One possible run:
Enter an integer: 123
Digits: 3The program handles 0 separately. If you only write while (num != 0), the loop will not run for input 0, and the digit count would incorrectly become 0.
Number guessing game
Another common while scenario is when the program does not know how many attempts the user will need. A number guessing game is a classic example. The program first creates a random answer, then keeps reading guesses. If the guess is too high, it prints a hint; if the guess is too low, it prints a different hint; when the guess is correct, break exits the loop.
std::mt19937 is the generator, and std::uniform_int_distribution<int> chooses integers from 1 to 100.#include <iostream>
#include <random>
int main() {
std::random_device device;
std::mt19937 generator(device());
std::uniform_int_distribution<int> distribution(1, 100);
int answer = distribution(generator);
int cnt = 0;
int num;
while (true) {
std::cout << "Guess a number: ";
std::cin >> num;
cnt++;
if (num > answer) {
std::cout << "Too high" << std::endl;
} else if (num < answer) {
std::cout << "Too low" << std::endl;
} else {
break;
}
}
std::cout << "Correct! You guessed " << cnt << " time(s)." << std::endl;
return 0;
}Here, while (true) creates a loop whose condition is always true. It does not stop by itself; the break inside the loop is what exits when the user guesses correctly.
do-while
C++ also provides the do-while loop. It puts the condition after the loop body, so it runs the body once first and then checks the condition, meaning it always runs at least once. Note the semicolon after while (condition); at the end -- it is easy to forget.
int num;
do {
std::cout << "Enter a positive number: ";
std::cin >> num;
} while (num <= 0);
std::cout << "You entered the positive number: " << num << std::endl;No matter what the user types first, the loop body runs once (it asks at least once); it only ends when the input no longer satisfies num <= 0 (that is, when a positive number is entered). This is ideal for menus, input validation, and other "ask at least once" scenarios.
| Loop | Checks condition first? | Minimum runs |
|---|---|---|
while | Yes | 0 |
do-while | No, runs the body first | 1 |