The Do...while Loop


We discussed in the previous section while constructing the while loop, a test of the condition before the loop becomes effective. Thus, the body of the loop cannot be applied effectively unless the condition is satisfied on the first attempt. In some cases, it may be necessary to execute the body of the loop before performing the test. Such a situation can be handled with the help of the do statement. It takes the form:

do
{
 //body of the loop
}
while(condition);

After reaching the do statement, the program first proceeds to evaluate the body of the loop. At the end of the loop, the condition is assessed in the while statement. If the condition is true then the program starts evaluating the loop's bid again. This process continues as long as the condition is true. If the condition is false, the loop will be closed and the control will move to the statement which will appear immediately after the while statement.

Since the condition is evaluated at the bottom of the loop, the do....while construct provides an exit-controlled loop, and therefore the body of the loop is always executed at least once.

Sample Program

Program
/* Reverse number program */
#include <stdio.h>

int main() {
  int number=153,rem,rev=0;
  printf("original number : %d\n",number);
  do
  {
   rem = number%10;
   rev = rev * 10 + rem;
   number /=10;
  }
  while(number > 0);
  printf("reverse number : %d",rev);
  return 0;
}