Loading lessons...
Do/While Loops
Do/While Loops
The do/while loop is the "at least once" loop: it runs the body first, then checks the condition.
The basic form
int i = 0;
do {
printf("%d\n", i);
i++;
} while (i < 5);
Output:
0
1
2
3
4
Key difference: always runs once
Even if the condition is false from the start, a do/while runs its body once:
int i = 10;
do {
printf("This prints once!\n");
} while (i < 5);
When is it useful?
Menus that must show at least once, validation that asks until the input is good, and "do this, then check if you should repeat".
while vs do/while
whilechecks first, may run zero times.do/whileruns first, checks after, always runs at least once.
TL;DR
do { ... } while (condition);runs the body at least once.- The condition is checked after each run.
- Great for menus and retry patterns.
- Remember the semicolon after the while!