The do-while Loop: Guaranteed First Execution
What you'll learn: How the do-while loop differs from while by always executing its body at least once, even if the condition is initially false.
The Key Difference
You've learned that a while loop checks its condition before running the loop body. If the condition starts out false, the body never executes. The do-while loop flips this around: it runs the body first, then checks the condition afterward.
Think of it like trying a sample at a grocery store. A regular while loop is like asking "Do I want to try this?" before tasting—you might say no and walk away. A do-while loop is like being handed the sample automatically—you taste it first, then decide if you want more.
Syntax
do {
// Loop body executes first
} while (condition);
Notice the semicolon after the condition—that's required syntax!
Basic Example
int count = 5;
do {
count++;
} while (count < 3);
// count is now 6, even though condition was false from the start
The body ran once (incrementing count from 5 to 6), then the condition count < 3 was checked and found false, so the loop stopped.
When to Use do-while
Use do-while when you need the loop body to execute at least once regardless of the initial condition. Common scenarios include menu systems or input validation where you must prompt the user at least once.
Key Takeaway: The do-while loop guarantees its body executes at least once by checking the condition after each iteration, making it ideal when a first execution is mandatory.