while & do-while Loops
while Loop
#include <iostream>
using namespace std;
int main() {
int count = 0;
while (count < 5) {
cout << count << " ";
count++;
}
cout << endl;
// Output: 0 1 2 3 4
return 0;
}do-while Loop
while(...).#include <iostream>
using namespace std;
int main() {
int count = 10;
do {
cout << count << " ";
count++;
} while (count < 5); // condition is false immediately...
cout << endl;
// Output: 10 <- body still ran once before checking
return 0;
}Loop | Condition checked | Runs body at least once? |
|---|---|---|
while | Before each iteration | No |
do-while | After each iteration | Yes |
Common Pattern: Input Validation
do-while shines when you need to do something at least once before you can even check the condition — the textbook example is asking a user for input and re-prompting until it's valid.
#include <iostream>
using namespace std;
int main() {
int age;
do {
cout << "Enter your age (0-120): ";
cin >> age;
} while (age < 0 || age > 120);
cout << "Thanks! You entered " << age << endl;
return 0;
}Common Pattern: Sentinel-Controlled Loop
A "sentinel" is a special value that signals the loop to stop. This is a classic use case for while, since you may not want the body to run at all if the very first input is already the sentinel.
#include <iostream>
using namespace std;
int main() {
int number;
int sum = 0;
cout << "Enter numbers to sum (-1 to stop): " << endl;
cin >> number;
while (number != -1) {
sum += number;
cin >> number;
}
cout << "Total: " << sum << endl;
return 0;
}// Bug: 'i' is never modified, so this never stops.
int i = 0;
while (i < 10) {
cout << i << endl;
// forgot: i++;
}Key Points
while checks its condition before the loop body runs, so the body may run zero times.
do-while checks its condition after the loop body runs, so the body always runs at least once.
do-while requires a trailing semicolon after while(condition);.
Sentinel loops and input validation are classic use cases for while and do-while, respectively.
Always ensure the loop body updates whatever the condition depends on, to avoid infinite loops.