c / beginner
Snippet
The do-while Loop
The do-while loop is similar to a while loop, but it evaluates its condition at the end of the loop body. This guarantees that the code block inside the loop is executed at least once, regardless of whether the condition is true or false initially.
snippet.c
1
2
3
4
5
int x = 0;do {printf("Executing...\n");x = 1;} while (x == 0);
Breakdown
1
int x = 0;
Initializes an integer variable named x to zero.
2
do { ... }
Starts the loop body which will execute before the condition is checked.
3
while (x == 0);
Checks the condition; if true, the loop repeats. Note the mandatory semicolon at the end.