A do...while loop executes its body first and checks the condition afterward. Because the test happens at the end, the body always runs at least once.
do {
// statements
} while (condition);
The semicolon after the closing while (condition) is required.
#include <stdio.h>
int main(void) {
int i = 1;
do {
printf("%d\n", i);
i++;
} while (i <= 5);
return 0;
}
Output
1
2
3
4
5
#include <stdio.h>
int main(void) {
int i = 50;
do {
printf("Executed once; i = %d\n", i);
} while (i >= 100);
return 0;
}
Output
Executed once; i = 50
This is the key difference from a while loop, which checks its condition before entering the body.
int i = 1;
do {
printf("%d\n", i);
// Missing i++ means i stays 1.
} while (i <= 5);
#include <stdio.h>
int main(void) {
int i = 1;
do {
if (i == 4) {
break;
}
printf("%d\n", i);
i++;
} while (i <= 5);
return 0;
}
Output
1
2
3
#include <stdio.h>
int main(void) {
int i = 0;
do {
i++;
if (i == 3) {
continue;
}
printf("%d\n", i);
} while (i < 5);
return 0;
}
Output
1
2
4
5
In a do...while loop, continue jumps to the condition check at the bottom.
#include <stdio.h>
int main(void) {
int i = 50;
do {
printf("%d\n", i);
i -= 10;
} while (i >= 0);
return 0;
}
Output
50
40
30
20
10
0
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.