for loop in c programming


  • The for loop allows to execute a set of instructions until a certain condition is satisfied. Condition may be pre-defined or open-ended.
  • A for loop is a repetition control structure that allows you to efficiently write a loop that needs to execute a specific number of times.

    Syntax of for loop:

    for(initialization; condition; increment/decrement)
    {
     statement ;
     statement ;
    }

Flow Diagram for loop:

    for loop in c

Explanation:

  • The for statement contains three expressions which are separated by semicolons. Following actions are to be performed in three expressions.
  • The initialize counter sets a loop to an initial value. This statement is executed only once.
  • The test condition is a relational expression that determines the number of iterations desired or it determines when to exit from the loop.
  • The for loop continues to execute as long as conditional test is satisfied. When the condition becomes false, the control of the program exits from the body of the for loop and executes next statement after the body of the loop.
  • The re-evaluation parameter decides how to make changes in the loop (quite often increment or decrement operations are to be used). The body of the loop may contain either a single statement or multiple statements.
  • In case there is only one statement after the for loop, braces may not be ¬≠necessary. In such a case, the only one statement is executed till the condition is satisfied.

    Example:

    #include <stdio.h>
    int main()
    {
       int i;
       for (i=1; i<=5; i++)
       {
           printf("%d\n", i);
       }
       return 0;
    }
    

    Output:

    1
    2
    3
    4
    5