Sunday, July 14, 2013

The for loop in C

In the Control Flow Statements, loops are one of the most useful and necessary part. Among the loops, for loop is the most familiar and used looping statement.

Syntax:

  • for(initial; condition; Increment)
  • {
  • //Statements to be executed
  • }
The above shown is the syntax of a for loop. A for loop contains three parts mainly.
  • initial is the initial conditions we maintain before a loop starts. These are mostly assignment operators. We assign some variables, which are necessary before the loop here.
  • condition is mostly a relation. This is the condition which controls, the loop. Based on the condition and its satisfaction, loop runs. If the condition is not satisfied, then the control gets out of loop.
  • increment is the operation, where in generally used to increment some value to know the loop counter or to change some values at each iteration.
And if there is only one statement, we can write directly, otherwise, we write the statements in between the curly braces({...}). 

Also we can nest for loops i.e., a loop inside another loop. Consider the following program to understand the for loop.

Example:
  1. #include<stdio.h>
  2. //Program to print two table
  3. main()
  4. {
  5. int i;
  6. for(i=1;i<=10;i++)
    1. printf("2 x %d = %d\n",i,2*i);
  7. return 0;
  8. }
The output of the above program is 
  • 2 x 1 = 2
  • 2 x 2 = 4
  • 2 x 3 = 6
  • 2 x 4 = 8
  • 2 x 5 = 10
  • 2 x 6 = 12
  • 2 x 7 = 14
  • 2 x 8 = 16
  • 2 x 9 = 18
  • 2 x 10 = 20
Thus we use for loops for controlled execution of set of statements. We use break and continue in this kind of loops for breaking out of looping or for continuing with next set of iteration.