This blog is under construction

Saturday, 21 April 2012

Loop control structure - for statement

The for statement is a loop statement which consists of three components namely initialization, expression and iteration.

Syntax:
for (initialization; expression; iteration) {
statement;
}
-----
-----
Below is the sequence of operation we do in for loop:
  1. Do initialization
  2. Evaluate the expression.  If the expression evaluates to be false, then go to step 6. Basically, for loop execution would end, program control would transfer to the statement next to for loop and the statements inside for loop won't get executed.
  3. If the expression evaluates to be true, then the statements inside the for loop will get executed.
  4. Once all statements inside for loop is executed, then iteration is done
  5. Continue from step 2
  6. End for loop execution
Basically, for loop is used to execute a block of code repeatedly until the given condition or expression evaluates to be false.

Example C program using "for Loop":
 
  #include <stdio.h>
  int main() {
        int i;
        for (i = 1; i <= 10; i++) {
        /*
         * i = 1   => initialization
         * i <= 10 => Expression
         * i++     => iteration
         */
                printf("%d\n", i); // execute this statement until i is less than or equal to 0
        }
        return 0;
  }

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



No comments:

Post a Comment