C do...while loop
UnlikeforandwhileLoops, they test the loop condition at the top of the loop. In C,do...whileThe loop checks its condition at the bottom of the loop.
do...whileThe do...while loop is similar to a while loop, but the do...while loop ensures that the loop is executed at least once.
Syntax
In C languagedo...whileThe syntax of loops:
do
{
statement(s);
}while( condition );
Note that the conditional expression appears at the bottom of the loop, so the statement(s) in the loop are executed at least once before the condition is tested.
If the condition is true, the control flow jumps back to the do above, and the statement(s) in the loop are executed again. This process repeats until the given condition becomes false.
Flowchart
Example
Example
#include <stdio.h>
int main ()
{
/* local variable definition */
int a = 10;
/* do loop executes at least once before the condition is tested */
do
{
printf("value of a: %d\n", a);
a = a + 1;
}while( a < 20 );
return 0;
}
int main ()
{
/* local variable definition */
int a = 10;
/* do loop executes at least once before the condition is tested */
do
{
printf("value of a: %d\n", a);
a = a + 1;
}while( a < 20 );
return 0;
}
When the above code is compiled and executed, it produces the following result:
a 的值: 10 a 的值: 11 a 的值: 12 a 的值: 13 a 的值: 14 a 的值: 15 a 的值: 16 a 的值: 17 a 的值: 18 a 的值: 19other extensions