C do-while Loop
Updated 7 min read Aimerscrew
A while loop checks its condition before doing anything, so it might never run. Sometimes that's wrong: you can't ask "do you want to play again?" before the first game has even started. The C do-while loop solves this by running the body first and checking the condition after. In this lesson, you'll learn its syntax, why it always runs at least once, and where it fits best: menus, PIN entry and "try again" prompts.
🌍 Real-life example
At an ATM, the machine always asks for your PIN at least once. Only after you type it does it check: correct? Let you in. Wrong? Ask again (up to a limit). Nobody checks a PIN that hasn't been entered yet. That "do it, then decide whether to repeat" pattern is exactly a do-while loop.
What is a do-while loop in C?
A do-while loop runs a block of code once, then keeps repeating it as long as a condition is true. The condition sits at the bottom:
do {
// loop body: always runs at least once
} while (condition);
Here's a small example that pours three cups of coffee:
#include <stdio.h>
int main(void) {
int cup = 1;
do {
printf("Pouring cup %d\n", cup);
cup++;
} while (cup <= 3);
printf("Coffee is served.\n");
return 0;
}
Pouring cup 1
Pouring cup 2
Pouring cup 3
Coffee is served.
The flow is: run the body, check cup <= 3, and if it's true, go back to do. Because the check comes last, the do-while loop is called an exit-controlled loop (or post-test loop).
Why does a do-while loop always run at least once?
Because C doesn't look at the condition until the body has finished. Compare both loops when the condition is false right from the start:
#include <stdio.h>
int main(void) {
int tickets = 0;
while (tickets > 0) {
printf("while: selling a ticket\n");
tickets--;
}
do {
printf("do-while: selling a ticket\n");
tickets--;
} while (tickets > 0);
printf("tickets = %d\n", tickets);
return 0;
}
do-while: selling a ticket
tickets = -1
The while loop printed nothing. The do-while loop ran its body once, even though there were no tickets, and pushed tickets down to -1. So a do-while loop is a great fit when the first run is required, and the wrong choice when "zero times" must be possible.
Don't forget the semicolon after while(...)
A do-while loop is the only loop in C that ends with a semicolon. The while (condition); line closes the whole statement, so the semicolon is required:
do {
printf("Hello\n");
} while (0); // the semicolon is required here
Leave it out and GCC stops with an error like expected ';' before ..., pointing at the next line. (A plain while loop is the opposite: a semicolon after while (...) there creates an empty loop, as you saw in the previous lesson.)
How do you build a "play again?" prompt?
Games almost always ask this question after a round, which makes it a natural do-while loop:
#include <stdio.h>
int main(void) {
char again = 'n';
int rounds = 0;
do {
rounds++;
printf("Playing round %d...\n", rounds);
printf("Play again? (y/n): ");
scanf(" %c", &again);
} while (again == 'y' || again == 'Y');
printf("Thanks for playing %d rounds!\n", rounds);
return 0;
}
In this run, the user typed y, then Y, then n:
Playing round 1...
Play again? (y/n): y
Playing round 2...
Play again? (y/n): Y
Playing round 3...
Play again? (y/n): n
Thanks for playing 3 rounds!
💡 Tip
Notice the space in " %c". When you press Enter, a newline character stays in the input. The space tells scanf to skip any whitespace (spaces, tabs, newlines) before reading the character. Without it, the second round would read the leftover newline instead of your answer.
PIN entry: input validation with a limit
Here's the ATM from the start of the lesson. The loop asks for a PIN, and repeats only if the PIN is wrong and the user still has attempts left:
#include <stdio.h>
int main(void) {
const int correct_pin = 4821;
int pin = 0;
int attempts = 0;
do {
printf("Enter your PIN: ");
scanf("%d", &pin);
attempts++;
} while (pin != correct_pin && attempts < 3);
if (pin == correct_pin) {
printf("Access granted after %d attempt(s).\n", attempts);
} else {
printf("Card locked. Too many wrong attempts.\n");
}
return 0;
}
In this run, the user typed 1234 and then 4821:
Enter your PIN: 1234
Enter your PIN: 4821
Access granted after 2 attempt(s).
If the user got it wrong three times, the loop would stop because attempts < 3 became false, and the if-else after the loop would print the "Card locked" message.
How do you make a menu loop in C?
Menus are the classic do-while use case: show the options, read a choice, act on it, and repeat until the user picks "Quit". A switch statement handles the choice nicely:
#include <stdio.h>
int main(void) {
int choice = 0;
double balance = 50.0;
do {
printf("1) Balance 2) Add $10 3) Quit\n");
printf("Choose: ");
scanf("%d", &choice);
switch (choice) {
case 1:
printf("Balance: $%.2f\n", balance);
break;
case 2:
balance += 10.0;
printf("Added $10.00\n");
break;
case 3:
printf("Goodbye!\n");
break;
default:
printf("Unknown option.\n");
}
} while (choice != 3);
return 0;
}
In this run, the user typed 2, then 1, then 3:
1) Balance 2) Add $10 3) Quit
Choose: 2
Added $10.00
1) Balance 2) Add $10 3) Quit
Choose: 1
Balance: $60.00
1) Balance 2) Add $10 3) Quit
Choose: 3
Goodbye!
The break statements here only leave the switch, not the loop. The loop ends because choice != 3 becomes false. You'll explore this difference in break and continue.
do-while vs while: what's the difference?
while | do-while | |
|---|---|---|
| Condition checked | Before the body | After the body |
| Minimum runs | 0 | 1 |
| Ends with a semicolon? | No | Yes: while (condition); |
| Also called | Entry-controlled / pre-test | Exit-controlled / post-test |
| Best for | Repeating while something is true, maybe never | Menus, prompts, "try again" input |
One more neat case: counting digits. The while version from the last lesson says 0 has 0 digits. A do-while loop divides at least once, so it correctly counts 1 digit:
#include <stdio.h>
int main(void) {
int number = 0;
int remaining = number;
int digits = 0;
do {
remaining /= 10;
digits++;
} while (remaining > 0);
printf("%d has %d digit(s).\n", number, digits);
return 0;
}
0 has 1 digit(s).
Common mistakes with do-while loops
1. Missing the final semicolon
} while (cup <= 3) without ; is a compile error. Read the last line of every do-while loop and check it ends with );.
2. Declaring the condition variable inside the body
do {
int pin = 0;
scanf("%d", &pin);
} while (pin != 4821); // error: 'pin' undeclared
A variable declared inside { } only exists inside those braces, and the while line is outside them. Declare pin before the do. You'll learn more in scope and storage classes.
3. Using do-while when zero runs must be possible
As the ticket example showed, a do-while loop runs once even when there's nothing to do. If an empty cart, an empty file or zero tickets must be handled, use a plain while loop.
4. Forgetting to change the condition
Just like a while loop, if nothing in the body changes the condition, the loop never ends. Press Ctrl+C to stop it, then add the missing update.
Practice exercise
🏋️ Try it yourself
Write a program that keeps asking the user for numbers and adds them up. It stops when the user enters 0, then prints the total. Use a do-while loop, since you always need at least one number.
Show solution
#include <stdio.h>
int main(void) {
int number = 0;
int total = 0;
do {
printf("Enter a number (0 to stop): ");
scanf("%d", &number);
total += number;
} while (number != 0);
printf("Total: %d\n", total);
return 0;
}
In this run, the user typed 12, 30, 8 and 0:
Enter a number (0 to stop): 12
Enter a number (0 to stop): 30
Enter a number (0 to stop): 8
Enter a number (0 to stop): 0
Total: 50
Adding the final 0 doesn't change the total, so it's safe to add before checking.
What's next?
You can now repeat code with for, while and do-while loops. Next, learn how to jump out of a loop early or skip a single iteration with C break and continue.
Key takeaways
- A do-while loop runs its body first and checks the condition afterward.
- The body of a do-while loop always runs at least once, even if the condition is false from the start.
- The loop ends with while (condition); and the semicolon is required.
- do-while is ideal for menus, "play again?" prompts and asking for input until it is valid.
- Variables used in the condition must be declared before the do, not inside the body.
- Use a plain while loop when the body must be able to run zero times.
Frequently asked questions
What is a do-while loop in C?
A do-while loop runs a block of code once and then repeats it as long as the condition at the bottom is true. Its syntax is do { body } while (condition); with a semicolon at the end.
What is the difference between while and do-while in C?
A while loop checks the condition before the body, so it can run zero times. A do-while loop checks after the body, so it always runs at least once.
Why is there a semicolon after while in a do-while loop?
The while (condition) line is the end of the do-while statement, and statements in C end with a semicolon. Without it, GCC reports an error.
When should I use a do-while loop?
Use it when the body must run before you can decide whether to repeat, such as showing a menu, asking "play again?", or reading a PIN or other input that must be checked after it is entered.
Is a do-while loop exit-controlled?
Yes. Because the condition is tested at the end of each iteration, a do-while loop is called an exit-controlled or post-test loop. while and for loops are entry-controlled.