do-while Loop
The do-while loop is a variant of
while that checks its condition after running the loop body instead of before. That single difference guarantees the body always executes at least once, which makes do-while the right tool whenever "run first, then decide whether to repeat" matches your problem better than "decide first, then maybe run."Syntax
C
#include <stdio.h>
int main(void) {
int count = 0;
do {
printf("count = %d\n", count);
count++;
} while (count < 5);
// Output: count = 0, count = 1, count = 2, count = 3, count = 4
return 0;
}Warning
Don't forget the semicolon after the closing
while(condition). Unlike a plain while loop, a do-while is a single statement that must be terminated with ; — omitting it is a compile error.The Key Difference From while
In a regular
while loop, the condition is checked before the first iteration, so the body might never run at all. In a do-while loop, the body always runs once before the condition is ever checked.C
int n = 10;
// while: condition checked first -- body never runs
while (n < 5) {
printf("while: never prints\n");
}
// do-while: body runs once regardless, THEN the condition is checked
do {
printf("do-while: prints exactly once\n");
} while (n < 5);Aspect | while | do-while |
|---|---|---|
Condition checked | Before the body | After the body |
Minimum executions | 0 | 1 |
Typical use | Loop may not need to run at all | Loop must run at least once |
Semicolon after condition | Not used | Required: while (cond); |
Practical Use Case: A Menu Loop
A textbook use of
do-while is a menu that must be shown to the user at least once, then repeated until they choose to exit. You cannot know whether to show the menu again until after you've shown it and read their choice — a perfect fit for check-after-the-body semantics.C
#include <stdio.h>
int main(void) {
int choice;
do {
printf("\n--- Menu ---\n");
printf("1. Say hello\n");
printf("2. Say goodbye\n");
printf("0. Exit\n");
printf("Choose an option: ");
scanf("%d", &choice);
switch (choice) {
case 1:
printf("Hello!\n");
break;
case 2:
printf("Goodbye!\n");
break;
case 0:
printf("Exiting...\n");
break;
default:
printf("Invalid option, try again.\n");
}
} while (choice != 0);
return 0;
}Note
The menu is always displayed at least once even before the user has made any choice at all — exactly the behavior a plain
while loop cannot express as directly, since it would need a duplicate copy of the menu-printing code before the loop to get the same effect.Key Points
do-while checks its condition after the body runs, guaranteeing at least one execution.
The closing while(condition) must be followed by a semicolon -- a commonly forgotten detail.
Use do-while when the loop body must run before there is anything meaningful to check.
Menu loops are the classic real-world example: show the menu, then decide whether to show it again.