For Loop

Back - C Language Notes By Vivek Sir email: vivekdubey22@gmail.com (w) 9826424484

Parts of for loop

Any repetition contains two important part - What to repeat and number of repetition? Variable-initialization, condition and variable-update define number of repetition and body of loop defines what to repeat.

·         Variable-initialization contain loop counter variable initialization statements. It define starting point of the repetition (where to start loop).

·         Condition contain Boolean expressions and works like if...else. If boolean expression is true, then execute body of loop otherwise terminate the loop.

·         Body of loop specifies what to repeat. It contain set of statements to repeat.

·         Variable-update contains loop counter update (increment/decrement) statements.

How for loop works?

·         Initially variable-initialization block receive program control. It is non-repeatable part and executed only once throughout the execution of for loop. After initialization program control is transferred to loop condition.

·         The loop condition block evaluates all Boolean expression and determines loop should continue or not. If loop conditions are met, then it transfers program control to body of loop otherwise terminate the loop. In C we specify a boolean expression using relational and logical operator.

·         Body of loop executes a set of statements. After executing all statements it transfer program control to variable-update block.

·         Variable-update block updates loop counter variable and transfer program control again back to condition block of loop.

Step 2 to 4 is repeated until condition is met.

Control Flow of for loop

#include <stdio.h>

void main()

{

    int count;

    for(count=1; count<=10; count++)

    {

        printf("%d ", count);

    }

}

 
For loop flowchart

Syntax of for loop

for(variable-initialization ; condition ; variable-update)

{

    // Body of for loop

}

Back - C Language Notes By Vivek Sir email: vivekdubey22@gmail.com (w) 9826424484