for loop in c with flow diagram and example code.

A for loop (Iteration statement) executes a statement or block of statements until the given condition is true. Including the for loop C language provides two more Iteration statements while and do while.

You can use any one of them for iteration but if you know the number of iteration, then you should use for loop and if you want to break the loop on the basis of the condition, then you should use a while loop.

Syntax of for loop in C:

//for loop syntax in C/C++

for (Expression1; Expression2; Expression3)
{

  //for loop body codes

}

In the above mention declaration,

Expression1: It is an initialization expression.

Expression2: It is the controlling expression that is evaluated before each execution of the for loop body.

Expression3: It is evaluated after each execution of for loop body. Generally, it is an increment statement.

 

You can read the article How to use the Increment operator in C.

 

Flow Diagram for loop

 

for loop in c

 

Example,

#include <stdio.h>

int main ()
{
    int loop =0;
    //Execution of for loop
    for( loop = 1; loop <= 10; ++loop)
    {
        printf("  10*%d = %d\n", loop, 10*loop);
    }

    return 0;
}

 

When we compile the above code then we will get the below output,

for loop in c

 

How the above program works:

Step 1: Initialize statement will execute first ( loop is initialized).

Step 2: Now controlling statements will execute and verify the condition.

Step 3: If the condition is true, then execute the loop body. If the condition is false then exit from the for loop body.

Step 4: The last step is to increment the value of the loop by 1 and repeat step2,step3, and step4.

Like another iteration statement, we can terminate for loop using the break, goto, and return keyword. We can also terminate an iteration without exiting the loop using the continue keyword.

#include<stdio.h>

int main()
{
    int loop = 0;

    for( loop =0 ; loop < 10 ; ++loop)
    {
        if(loop == 2)
        {
            break; // terminate loop
        }
        printf("Value of loop = %d\n", loop);
    }

    return 0;
}

 

Output:

Value of loop = 0
Value of loop = 1

 

Statements within the for loop are optional, we can omit these statement according to the requirement. If we remove all the statements then it becomes an infinite loop.

// Infinite loop using the for loop


for(;;);  

  OR

for(;;)
{

}

 

Recommended Articles for you: