C++ Do/While Loop
Introduction to Do/While
The do-while
loop is similar to a while
loop, but it guarantees that the loop body executes at least once.
The condition is evaluated after each iteration, making it useful when code must always run at least one time before checking the condition.
Basic Syntax
General form of a do-while
loop (note the mandatory semicolon after the closing parenthesis):
do {
// code to execute at least once
} while (condition);
Simple Example
This example forces the user to enter a positive number. The prompt will always appear at least once.
#include <iostream>
using namespace std;
int main() {
int number;
do {
cout << "Enter a positive number: ";
cin >> number;
} while (number <= 0);
cout << "You entered: " << number;
return 0;
}
Enter a positive number: -5 Enter a positive number: 0 Enter a positive number: 7 You entered: 7
Robust Input Validation
When reading from std::cin
, a failed extraction (e.g., non-numeric input) sets the stream’s failbit and leaves the variable unchanged. Clear the error and discard bad input before the next iteration.
#include <iostream>
#include <limits>
using namespace std;
int main() {
int number = 0;
do {
cout << "Enter a positive number: ";
if (!(cin >> number)) {
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
cout << "Invalid input. Try again.\n";
number = 0; // keep loop going
}
} while (number <= 0);
cout << "You entered: " << number << '\n';
}
Key Differences from While
The main differences between while
and do-while
:
While Loop | Do/While Loop |
---|---|
Condition checked before iteration | Condition checked after iteration |
May execute zero times | Always executes at least once |
Common for most pre-check loops | Preferred when at least one execution is required |
Menu-Style Example
A classic use case is interactive menus that should display at least once and repeat until the user chooses to exit.
#include <iostream>
using namespace std;
int main() {
int choice;
do {
cout << "\n=== Menu ===\n";
cout << "1. Start\n2. Settings\n0. Exit\n";
cout << "Choice: ";
cin >> choice;
switch (choice) {
case 1: cout << "Starting...\n"; break;
case 2: cout << "Opening settings...\n"; break;
case 0: cout << "Goodbye!\n"; break;
default: cout << "Invalid choice.\n"; break;
}
} while (choice != 0);
}
=== Menu === 1. Start 2. Settings 0. Exit Choice: 2 Opening settings... === Menu === 1. Start 2. Settings 0. Exit Choice: 0 Goodbye!
Common Pitfalls
- **Stray semicolon after do
:** do ; while (cond);
loops an empty body; the block following it is not part of the loop.
- **Forgetting the required semicolon** after while (condition)
.
- **Unchanged loop state:** if the body never changes values used by the condition, the loop may never terminate.
- **Input failures with cin
:** once the stream is in a fail state, extractions continue to fail until cleared.
// Wrong: empty loop; the block runs once after the loop finishes
int i = 0;
do ; while (++i < 3);
{
// This is NOT in the loop
}
// Right: the block is the loop body
do {
// body
} while (++i < 3);
Common Use Cases
- Input validation (as shown above)
- Interactive menus
- Game loops that need an initial update tick
- Repeating tasks until the user signals exit