C do while loop
In while loop the body of the loop may not be executed if the condition is not true at the very first attempt. But sometime it will be needed to execute the body before the test is performed. Such situations can be handled using the do while loop. The general form is:
Syntax
do {
body of the loop
}
while (test_condition);
Here in the do statement the program evaluates the body of the loop first then the test_condition in the while statement is evaluated. If the condition is true then the program once again executes the body of the loop. The process will repeat again and again until the test_condition becomes false. When the test_condition finally becomes false the control will be transferred out of the loop and continues with the statement immediately after the while statement.
Flowchart of do while loop:
Example of a do while loop:
Example:
#include <stdio.h>
int main()
{
int i = 1;
do {
printf("%d\n", i);
i++;
}
while(i <= 10);
return 0;
}
Output:
1 2 3 4 5 6 7 8 9 10