C programming tutorial

                 PREVIOUS                                                                                   NEXT CHAPTER

While loop

 

For loop is generally used when we know in advance that how many times will the loop run.while loop is used when we dont know how many time loop will run.

While loop syntax in C

while(condition)

{
//statements;
}
In while loop firstly condition is checked.If condition is true then statements inside while loop are execute otherwise loop terminated.

Example:

int i=0;
while(i<3)
{
printf(" while loop C ");
i++;
}
In above example.
  1. condition is checked ,since i=0 hence less then 3,statements inside while loop are executed.it will print while loop C.i is incremented by 1.
  2. now i=1 ,still less then 3,again print the statement,i is incremented by 1
  3. now i=2 ,still less then 3,again print the statement,i is incremented by 1
  4. now i=3,its not less then 3,hence while loop is terminated
int i=0;
while(1)
{
printf(" while loop C");
i++;
}

If we will write 1 or any other non zero number in place of condition .Non zero number represent true in C. hence condition is always true.It will print statement infinite times.

To stop the infinite loop press ctrl + break.
If we write 0 in place of 1. 0 represent false in C .hence while loop will not run.

 



                 PREVIOUS                                                                                   NEXT CHAPTER