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

  1. do {
  2. body of the loop
  3. }
  4. 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:


flowchart of do while loop


Example of a do while loop:

Example:

  1. #include <stdio.h>
  2. int main()
  3. {
  4. int i = 1;
  5. do {
  6. printf("%d\n", i);
  7. i++;
  8. }
  9. while(i <= 10);
  10. return 0;
  11. }

Output:

1
2
3
4
5
6
7
8
9
10