C Do While Loop
A do while loop repeats its block and always runs it at least once. A while loop checks first and may run zero times; this loop checks after each round instead.
Run once at least
Count runs from 1 to 3, and the check runs after each round. The loop stops when count passes 3.
#include <stdio.h>
int main() {
int count = 1;
do {
printf("%d\n", count);
count++;
} while (count < 4);
return 0;
}Check false at start
Count begins at 10, so the check fails after the first round. The block still ran once, so 10 prints before Done.
#include <stdio.h>
int main() {
int count = 10;
do {
printf("%d\n", count);
count++;
} while (count < 4);
printf("Done.\n");
return 0;
}Add numbers with do while
Total grows by 1, then 2, then 3 across the three rounds. The print line shows the total: 6.
#include <stdio.h>
int main() {
int total = 0;
int n = 1;
do {
total = total + n;
n++;
} while (n < 4);
printf("%d\n", total);
return 0;
}Example
#include <stdio.h>
int main() {
int count = 3;
do {
printf("%d\n", count);
count--;
} while (count > 0);
printf("Go!\n");
return 0;
}Key points
- A do while loop starts with the word do and a block in curly braces.
- The word while and the check come after the block.
- The block runs once before the check is ever tested.
- The loop repeats when the check is true, and stops when it is false.
- A semicolon follows the check at the end of a do while loop.
- Use a do while loop when the block must run at least once.
Count starts at 3 and falls by 1 each round, with the check running after. At 0 the loop ends, and Go! prints last.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
Count starts at 10. The loop is do { count prints, then count grows by 1 } while (count < 4); How many times does the block run?