Do/While Loop
Lesson outline
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):
Simple Example
This example forces the user to enter a positive number. The prompt will always appear at least once.
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.
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.
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.
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