While loop in C


The While loop


This is an entry controlled looping statement. It is used to repeat a block of statements until condition becomes true.
In this, first of all condition is checked and if it is true then group of statements or body of
loop will be executed. It will execute again and again till condition becomes false.

Syntax :

while(condition)
{
statements;
increment/decrement;
}

In above syntax, the condition is checked first. If it is true, then the program control flow goes inside the loop and executes the block of statements associated with it. At the end of loop increment or decrement is done to change in variable value. This process continues until test condition satisfies.

The operation of the while loop is illustrated in the following figure.





















Simple Example :

#include <stdio.h>
#include <conio.h>

void main()
{
int x;
clrscr();
x=1;
while(x<=5)
{
printf("\nHi");
x = x + 1;
}
getch();
}

Output :









Description :

Here the value of x is 1. Now the compiler will check the while condition, since 1 is less than 5, hence the control goes into the while loop and will print 'Hi', then the next statement x=x+1 will execute which change the value of x=2 and the control again goes to check the condition of while loop which is again comes out to be true as 2 is less than 5 and hence it will again print 'Hi'. Similarly this process continous until the value of x is greater than 5 that is when the value of x becomes 6 then the condition will false and hence the control will be out of the while loop.
Hence 5 times 'Hi' is printed and in the print statement we has used the '\n' escape sequence which means next line hence the every 'Hi' is printed in new line.

Note :

We will discuss more programs in our C programs section.


     Prev                                                   NEXT

0 comments:

Post a Comment