While Loop in C Programming (Syntax and Example)

WHILE - WHILE loops are very simple.
The basic structure is

while ( condition ) 
Code to execute while the condition is true 

The true represents a boolean expression which could be x == 1 or while ( x != 7 ) (x does not equal 7). It can be any combination of boolean statements that are legal. Even, (while x ==5 || v == 7) which says execute the code while x equals five or while v equals 7. Notice that a while loop is like a stripped-down version of a for loop-- it has no initialization or update section. However, an empty condition is not legal for a while loop as it is with a for loop.

#include <stdio.h>

int main()
  int x = 0;  /* Don't forget to declare variables */
  while ( x < 10 ) 
  { /* While x is less than 10 */
      printf( "%d\n", x );
      x++;             /* Update x so the condition can be met eventually */
This was another simple example, but it is longer than the above FOR loop. The easiest way to think of the loop is that when it reaches the brace at the end it jumps back up to the beginning of the loop, which checks the condition again and decides whether to repeat the block another time, or stop and move to the next statement after the block. 


Popular posts from this blog



HSC Exam Time Table 2013 Arts, Commerce, Science