Loops in C-Programing


Next >>

A loop is used to execute the block of code or part of program several times.

Types of Loops in C

  • for loop
  • while loop
  • do...while loop

for loop

The for loop has a general form

 for(expr1 ; expr2; expr3)
  • The for loop has an optional expr1, expr2 and expr3 but the semicolon is compulsary.
  • The expr1 is used to initialize the control variable and it is executed only once.
  • The expr2 is a condition that is to be evaluated.
    • If the condition is false, then the for loop is terminated.
    • If the condition is true, the code inside the for loop body will be executed.
  • The expr3 is a statement that is updated every execution. Usually,this expression is a increment or decrement but can be any expression. This process will repeat until the condition expr2 becomes false.


If the expr1 and expr3 are omitted, then this for loop behaves like while loop.

If the expr2 is omitted, then the condition is always TRUE and we have an infinity loop as result.

for ( ; ; )     /*infinity loop */

Example C Program using for loop


int main()
  int a;
  for ( a = 0; a < 5; a++)
    printf("The value of a = %d\n",a);

  printf("The final value of a = %d\n",a);




When you compile and execute the above program, you will get the following output:

<< Previous

Next >>