Converting a while loop to a do-while
What you'll learn: How to restructure a standard loop to ensure the code block runs at least once before checking the condition.
The "Check First" vs. "Act First" Approach
In the previous lessons, we looked at the while loop. Think of a while loop like a security guard standing at the entrance of a club. He checks your ID (the condition) before he lets you inside. If you don't meet the requirements, you never step foot on the dance floor.
A do-while loop flips this logic. It is like a restaurant where you sit down and start eating, and the waiter only checks if you have enough money to stay for the next course after you've finished the first one. You are guaranteed at least one "bite" no matter what.
Making the Switch
To convert a while loop to a do-while, you essentially move the condition from the top to the bottom.
- Take the
while(condition)statement and move it to the very end of the code block. - Add a semicolon
;after the closing parenthesis of the condition. (This is a common mistake—standardwhileloops don't need a semicolon here, butdo-whileloops do!) - Place the keyword
doat the very top where the loop starts.
A Practical Example
Imagine you are writing a program that asks a user to press 'q' to quit. In a standard while loop, you have to initialize your variable to a "dummy" value just to get inside the loop. With a do-while, the code is much cleaner because the prompt happens naturally before the check.
#include <stdio.h>
int main() {
char choice;
// The code INSIDE the braces runs first
do {
printf("Processing data... Press 'q' to quit: ");
scanf(" %c", &choice);
// The condition is checked AFTER the code runs
} while (choice != 'q');
printf("Goodbye!");
return 0;
}
In the example above, if we used a regular while loop, we would have to ask for the user's input once before the loop even started. By converting it to a do-while, we avoid repeating ourselves. The program performs the action, then decides if it should repeat.
Key takeaway
Use a do-while loop when you want the body of your loop to execute at least once, regardless of whether the condition is initially true or false.