The C do-while loop is a different kind of loop which checks for exit conditions instead of entry condition. So it is very useful if you want a loop that keep iterating until an exit criteria is met.
In a C program, the do-while loop will let you execute you code first and then checks for test condition if it is true to complete the execution.
If the test condition is false, loop terminates and ignores any computation it may have performed previously.
Diagram for C Do-While Loop
The diagram below is used for Do-While loop when we create a flowchart for C program.
int main ()
int i, sum;
/* Initialization of loop variable 'i' and sum */
i = 0;
sum = 0;
/* Do-while loop body execution starts */
sum = sum + i;
/* Increment the loop */
} while (i < 10); /* check for exit condition */
printf ("\t\t\tThe sum is %d", sum);
Output – C Do-While Loop
In the above example, the do-while is initialized like other loop control structures – for and while loop. The variable sum is also initialized to 0.,/p>
sum = 0;
Then, the do block is started with executing the following statement. Unlike other loops, the do-while does not check for entry conditions and directly execute the loop body.
Next, the do-while loop is incremented for next iteration.
When all the tasks in a do block is completed the while condition checks for the Boolean value of the loop and decides to continue if true or terminates the do-while loop if false.
The program then prints the output, when the loop terminates.
and the program ends.
Balagurusamy, E. 2000. Programming in ANSI C. Tata McGraw-Hill Education,.
Kanetkar, Yashavant. 20 November 2002. Let us C. Bpb Publications.