This blog is under construction

Saturday, 21 April 2012

Loop control structure - while statement

while is also a loop statement which evaluates the expression at the beginning of the loop.  If the expression evaluates to be false, then the loop terminates.  Otherwise, the statements inside the loop will get executed.  This cycle continues until the expression evaluates to be false.  In the case of while loop, initialization is performed before the while loop and the iteration is performed inside the while loop.

Syntax for while loop:
while (expression) {
       ---------------------
           <Statements>
       ---------------------
}

Basically, while loop is used to execute a block of statements until expression becomes 0.

Example C program using while loop:
 
  #include <stdio.h>
  int main() {
  int main() {
        int i = 1;  // Initialization
        while (i <= 10) {   // expression => i<=10
                printf("%d\n", i);
                i++; // incrementing the value of i
        }
        return 0;
  }

  Output:
  jp@jp-VirtualBox:~/$ ./a.out
  1
  2
  3
  4
  5
  6
  7
  8
  9
  10



No comments:

Post a Comment