Monday, July 15, 2013

The while loop in C

In C, while loop is one of the looping statements which is used most. In while, unlike for, we need not mention the initial and increment statements. We directly specify the condition which is to be met and the loop continues to execute until that condition fails.

In some situations, while loop is better than for loop. But in most of the case, for loop is better than while.
Syntax:

  • while(condition)
  • {
  • //Statements
  • }
The only thing we have to care about the syntax of the while loop is the condition. This condition is generally a relational condition. In such a condition, we need to maintain condition that would definitely failed at some point. Because if this condition doesn't fail, then the loop continues to run and doesn't terminate. That is not good practice to do that. 

An example for using a while loop.
Example:
  1. #include<stdio.h>
  2. main()
  3. {
  4. int a;
  5. while(a!=1)
  6. {
  7. printf("Press 1 to stop loop else any number");
  8. scanf("%d",&a);
  9. }
  10. return 0;
  11. }
In the above example, if a is 1, then the condition fails, else the loop runs.

We can come out of loop only if the condition fails. However, we can get out of the loops with break and continue to the next iteration by using a continue.