The While Loop


The simplest of all the looping structures of C is the while statement. We have used while statements in our previous tutorial programs. The main format of the time statement is:

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

The while loop is an entry-controlled loop statement. The condition is evaluated and if the condition is true then the body of the loop is executed. After the body is executed, the condition is re-evaluated and if it is true, the body is executed again. This process of repeated execution of the body continues until the condition is eventually false and the control is not transferred out of the loop. Upon exit, the program continues with the statement along with the body of the loop.

The body of the loop may contain one or more statements. Only braces are needed if there are two or more statements in the body, but it is a good practice to use brackets even if the body has only one statement.

Sample Program

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

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