C do-while Loop
In this page:
What is a do-while Loop?
A do-while loop is a post-test loop: it runs its body first and only checks the condition afterward, guaranteeing at least one execution even if the condition would have been false from the very start.
Example: What is a do-while Loop?
#include <stdio.h>
int main() {
int x = 10;
do {
printf("Runs at least once");
} while (x < 5);
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Simple Countdown
You can print a countdown sequence with a do-while loop by decrementing the counter inside the body on each pass, similar to a while loop, but with the guarantee that the first value is always printed at least once.
Example: Simple Countdown
#include <stdio.h>
int main() {
int i = 5;
do {
printf("%d ", i);
i--;
} while (i >= 1);
return 0;
}
Login to try C/C++/Java/PHP code in the editor
User Input Validation
do-while is well suited for input validation, since you typically need to prompt the user and read their input at least once before you have anything to check -- a plain while loop can't guarantee that first prompt happens.
Example: User Input Validation
#include <stdio.h>
int main() {
int value;
do {
sscanf("7", "%d", &value);
} while (value < 0);
printf("%d", value);
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Sum Accumulation
Just like a while loop, a do-while loop can accumulate a running total across iterations by updating a sum variable inside its body each time it executes.
Example: Sum Accumulation
#include <stdio.h>
int main() {
int i = 1, sum = 0;
do {
sum += i;
i++;
} while (i <= 5);
printf("%d", sum);
return 0;
}
Login to try C/C++/Java/PHP code in the editor
while vs. do-while
The key difference from a while loop is timing: while checks its condition before the first run and may execute zero times, while do-while checks after the first run and always executes at least once.
Example: while vs. do-while
#include <stdio.h>
int main() {
int x = 10;
while (x < 5) {
printf("while: never runs\n");
}
do {
printf("do-while: runs once");
} while (x < 5);
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 11 topics to unlock
0/11 topics done
Complete these topics first: