C Language

Do While Loop

In C Language by Baqir Ali

When a loop is constructed using a while statement, the test for the continuation of the loop is carried out at the beginning of each pass. Sometimes however, it is desirable to have a loop where the test for continuation takes place at the end of each pass.

General Form of do while loop:

 while (expression); 

where expression represents a condition that must be true for the loop to continue execution and the statement is executed repeatedly, as long as the expression is true.

  • Note, however, that the statement is always executed at least once, since the test for repetition does not take place until the end of the first pass through the loop.

The statement can be either simple or compound, and should, of course, include some feature that eventually alters the value of the expression.

 } while (expression); 

Summing 10 numbers using do while loop

void main (void)
   int i = 1, sum = 0;
      sum = sum + i;
      i = i + 1;
   }while (i <= 10);
   printf(“Sum = %d\n”, sum); 

What are the differences between while and do-while loops?

  • while loops and do-while loops are similar.
  • The difference between the two loops is that, in the while loop, the expression is tested first, and, if the expression result is false, the loop body is not executed.
  • However, in the do-while loop, the loop body is always executed once. After that, the expression is tested; if the test result is false, the loop body is not executed again.

Get The Coding Examples From C Language Code Example Page