The while & do-while Loops
The while & do-while Loops
The for loop is ideal when you know in advance how many iterations you need. But what if you do not know the count — what if you want to keep asking a user for input until they type a valid number, or keep reading records until the data runs out? That is where the while and do-while loops shine.
The while Loop — Entry-Controlled
A while loop checks its condition before each iteration. If the condition is false right from the start, the body never runs at all.
The structure has three parts you must manage yourself:
- Initialise the variable before the loop (
int count = 1). - Test the condition at the top of each iteration.
- Update the variable inside the body so the condition eventually becomes
false.
count++ were missing in the example above, the condition count <= 5 would stay true forever and your program would hang. Always verify that your loop body moves toward the exit condition.
Sentinel Values
A sentinel value is a special input the user types (or a special data value your program encounters) that signals "stop the loop." This is one of the most practical uses of while.
while loops.
The do-while Loop — Exit-Controlled
A do-while loop places the condition after the body. This guarantees the body executes at least once, even if the condition is immediately false.
Without do-while you would have to either duplicate the prompt before the loop or use a workaround. The exit-controlled design is a natural fit whenever the body must run once to produce the value that the condition checks.
while vs do-while — When to Use Each
- Use
whilewhen the loop might not need to run at all (e.g., process a file that could be empty). - Use
do-whilewhen the loop body must always run at least once (e.g., show a menu before checking the user's choice).
Avoiding Infinite Loops
Every loop needs a guaranteed exit path. Ask yourself three questions before you write any while loop:
- What variable or condition controls the loop?
- Is that variable modified inside the body?
- Will the modification eventually make the condition
false?
Summary
The while loop is entry-controlled: the condition is checked first and the body may never execute. The do-while loop is exit-controlled: the body always runs at least once. Sentinel values give while loops a clean, user-driven exit condition. Always ensure your loop body moves toward the exit condition to prevent infinite loops.