The do-while loop is C’s post-test loop: the body runs first, then the condition is checked. That guarantees at least one execution—perfect for menus and input validation where you must prompt before you can test whether to continue.
01
Syntax
do { } while.
02
Post-test
Check after.
03
Once min
Always runs.
04
Validation
Retry input.
05
Menus
Show first.
06
;
Required.
Fundamentals
Definition and Usage
A do-while loop executes its body, then evaluates the condition. If the condition is true, the loop repeats; if false, control moves to the next statement. Because the test comes after the body, the body always runs at least once.
Compare with while: if the condition is false before the first test, a while loop skips the body entirely. do-while still runs the body once. That difference matters for prompts, menus, and “try at least once” logic.
💡
Beginner Tip
Do not forget the semicolon after while (condition);—it is required syntax, not a mistake. The whole statement is do { ... } while (expr);.
Foundation
📝 Syntax
General form of the C do-while loop:
C
do {
// statements to repeat
} while (condition);
Parts
do — starts the loop; body runs immediately.
{ ... } — block executed on each iteration.
while (condition); — tested after the body; semicolon required.
Equivalent counting pattern
C
int i = 0;
do {
printf("%d\n", i);
i++;
} while (i < 5);
Compile
C
gcc program.c -std=c11 -o program
Cheat Sheet
⚡ Quick Reference
Pattern
Example
Basic do-while
do { ... } while (i < n);
Input validation
do { scanf(...); } while (n < 1 || n > 10);
Menu until exit
do { show menu; } while (choice != 0);
vs while
do-while runs body at least once
Required punctuation
Semicolon after while (cond);
Post-test
run, then check
do-while
Minimum
1 iteration
Guaranteed
vs while
0 or more
while body
End
while (c);
Need ;
Hands-On
Examples Gallery
Compile with gcc example.c -std=c11 -o example. Notice how each pattern benefits from running the body before the first condition test.
📚 Getting Started
Standard counting and the key “at least once” behavior.
Example 1 — Print Numbers 0 to 4
Same output as a for or while loop, written with do-while.
C
#include <stdio.h>
int main(void) {
int i = 0;
do {
printf("%d\n", i);
i++;
} while (i < 5);
return 0;
}
📤 Output:
0
1
2
3
4
How It Works
The body prints and increments i. After each pass, i < 5 is tested. When i reaches 5, the condition fails and the loop stops.
Example 2 — Body Runs Even When Condition Starts False
This shows the difference from while: the body executes once even though i < 5 is false from the start.
C
#include <stdio.h>
int main(void) {
int i = 10;
do {
printf("Body runs: i = %d\n", i);
i++;
} while (i < 5);
printf("After loop: i = %d\n", i);
return 0;
}
📤 Output:
Body runs: i = 10
After loop: i = 11
How It Works
A while (i < 5) loop would skip the body entirely here. do-while runs once, then checks the condition, finds it false, and exits.
📈 Practical Patterns
Validation, menus, and interactive programs.
Example 3 — Validate Input Between 1 and 10
Prompt at least once; repeat until the user enters a valid number.
C
#include <stdio.h>
int main(void) {
int num;
do {
printf("Enter a number between 1 and 10: ");
if (scanf("%d", &num) != 1) {
return 1;
}
} while (num < 1 || num > 10);
printf("You entered: %d\n", num);
return 0;
}
📤 Output (sample run):
Enter a number between 1 and 10: 0
Enter a number between 1 and 10: 15
Enter a number between 1 and 10: 7
You entered: 7
How It Works
The prompt always appears before the first check. Invalid values cause another iteration; valid input makes the condition false and exits.
Example 4 — Menu with switch
Display a menu at least once; keep going until the user chooses exit.
C
#include <stdio.h>
int main(void) {
int choice;
do {
printf("\nMenu:\n");
printf("1. Option 1\n");
printf("2. Option 2\n");
printf("3. Exit\n");
printf("Enter your choice: ");
if (scanf("%d", &choice) != 1) {
break;
}
switch (choice) {
case 1:
printf("Option 1 selected.\n");
break;
case 2:
printf("Option 2 selected.\n");
break;
case 3:
printf("Exiting...\n");
break;
default:
printf("Invalid choice, try again.\n");
}
} while (choice != 3);
return 0;
}
📤 Output (sample run):
Menu:
1. Option 1
2. Option 2
3. Exit
Enter your choice: 1
Option 1 selected.
Menu:
1. Option 1
2. Option 2
3. Exit
Enter your choice: 3
Exiting...
How It Works
The menu shows before the exit test. choice != 3 keeps the loop alive; selecting 3 prints a message and ends the loop on the next condition check.
Example 5 — Play Again Prompt
Run a mini game, then ask whether to play again—classic do-while shape.
C
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main(void) {
char again;
srand((unsigned)time(NULL));
do {
int secret = rand() % 10 + 1;
int guess;
printf("Guess a number 1-10: ");
if (scanf("%d", &guess) != 1) {
break;
}
if (guess == secret) {
printf("Correct! It was %d.\n", secret);
} else {
printf("Wrong. The number was %d.\n", secret);
}
printf("Play again? (y/n): ");
if (scanf(" %c", &again) != 1) {
break;
}
} while (again == 'y' || again == 'Y');
printf("Thanks for playing!\n");
return 0;
}
📤 Output (sample run):
Guess a number 1-10: 4
Wrong. The number was 7.
Play again? (y/n): n
Thanks for playing!
How It Works
The game always runs at least one round. The loop continues only when the player answers y or Y after the round ends.
Applications
🚀 Common Use Cases
Input validation — prompt, read, retry until valid.
Menus — show options before checking exit choice.
Play again — run activity, then ask to repeat.
Hardware polling — attempt operation once, retry while busy.
Password retry — at least one login attempt.
Parser peek — read token, continue while more input exists.
🧠 How the do-while Loop Works
1
Run body
Execute statements inside do { } first.
Always once
2
Test condition
Evaluate while (condition) after the body.
Post-test
3
True?
If yes, jump back to step 1. If no, continue program.
Repeat?
=
✅
At least one pass
Unlike while, the body never runs zero times.
Important
📝 Notes
Semicolon after while (condition); is mandatory.
Body runs at least once even if the condition starts false.
Update variables inside the body so the condition can eventually fail.
break and continue work inside do-while like other loops.
Prefer while when zero iterations is correct; use do-while when it is not.
Check scanf return values in validation loops.
Performance
⚡ Optimization
do-while has the same runtime cost as an equivalent while loop for repeated iterations. Choose based on clarity, not speed. For validation, combine the prompt and read in the body once per iteration rather than duplicating code before a while loop.
Wrap Up
Conclusion
The C do-while loop guarantees at least one execution before the condition is tested. Use it for menus, validation, and any task where the first pass must happen before you can decide to repeat.
You have now covered all three C loop forms—for, while, and do-while. Pick the one that matches how your condition and counter are structured.
Create infinite loops with a never-false condition
Forget to update variables the condition uses
Choose do-while only because it looks shorter
Summary
Key Takeaways
Knowledge Unlocked
Five things to remember about the C do-while loop
Post-test repetition with a guaranteed first pass.
5
Core concepts
📝01
Post-test
Check after.
Basics
✅02
Min 1 run
Always.
Key rule
⌨03
Validation
Retry input.
Pattern
📋04
Menus
Show first.
UI
;05
Semicolon
Required.
Syntax
❓ Frequently Asked Questions
A do-while loop runs its body at least once, then checks the condition. Syntax: do { ... } while (condition); The semicolon after the closing parenthesis is required. If the condition is true, the loop repeats.
while tests the condition before the body—the body may run zero times. do-while tests after the body—the body always runs at least once. Use do-while when you must execute the block before knowing whether to continue.
The do-while statement ends with while (expression); — the semicolon is part of the syntax, not an empty statement. Omitting it is a compile error.
Use do-while for input validation prompts, menus that must display once, and any logic where the first pass must happen before you can test the stop condition.
Yes. If the condition is false after the first execution, the loop exits. It runs at minimum one time and at maximum until the condition becomes false.
No. while (1) can loop forever without a break. do-while always evaluates a real condition after each iteration and is the idiomatic choice when you need guaranteed first execution with a clear exit test.
Did you know?
C is one of few languages where do-while ends with a mandatory semicolon after the closing parenthesis. That semicolon completes the do-whilestatement—it is not an extra empty statement after the loop.