Comparing while vs do-while use cases
What you'll learn: How to choose the right loop structure based on whether you need to check a condition before or after running your code.
In previous lessons, we learned that loops repeat actions. However, the biggest difference between a while loop and a do-while loop is the "entrance fee."
The "Look Before You Leap" Approach
A standard while loop is cautious. It checks the condition at the very beginning. If the condition is false right away, the code inside the loop never runs.
Think of a while loop like a high-end club with a bouncer at the door. If you don't have an invite (the condition is false), you don't even get to step inside. This is perfect for scenarios like processing a file; if the file is empty, you don't want to start reading it.
The "Shoot First, Ask Questions Later" Approach
A do-while loop is different. It executes the body of the loop first and checks the condition at the end. This means the code inside a do-while loop is guaranteed to run at least once, no matter what.
Think of this like a "Free Trial" or a restaurant where you pay after you eat. You get the experience first, then the "bouncer" checks your wallet at the exit to see if you can stay for seconds.
A Concrete Example: User Input
The most common use case for a do-while loop is menu selection. You need to show the user the menu at least once before you can check if they want to quit.
#include <stdio.h>
int main() {
int choice;
// We use do-while because we MUST show the menu at least once
do {
printf("1. Save\n");
printf("2. Load\n");
printf("0. Exit\n");
printf("Enter choice: ");
scanf("%d", &choice);
printf("You chose %d\n", choice);
} while (choice != 0); // Only stop if they choose 0
return 0;
}
In this example, using a regular while loop would be clunky because you’d have to initialize choice to a "dummy" value just to get past the first check. The do-while loop makes the logic cleaner: do the action, then decide if it needs to happen again.
Key takeaway
Use while when the code might not need to run at all; use do-while when the code must run at least once before the condition is checked.