For Loop

Syntax:

for(initialization; condition; increment/decrements)
{
   // statements should be repeated
}

There are three parts inside for loop: initialization,condition,increment/decrements. Each part is separated by a semicolon. statements inside { } will be repeated based on these three parts. Initialization part will set a initial value to a variable, condition part will set a condition to be checked before executing statements inside {}. increment/decrements will update the initial value of the variable. One repetition of a loop is called one iteration.

Example:

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

OUTPUT

Iteration 1
Iteration 2
Iteration 3
Iteration 4

Explanation of for loop:
First iteration:
i=1; will execute first and i is initialized by 1 then condition part is checked. Here condition is i<5 and value of i is 1. So 1<5 is true. Hence condition is true statements inside { } will be executed. In our case printf(“Iteration %d\n”,i); will be executed. %d will be replaced by value of i. So printf(“Iteration %d\n”,i); is equivalent to printf(“Iteration 1\n”); for first iteration. Second iteration:
Now i++ will be executed.So value of i will be increment by 1 and new value is 2. Now condition will be checked. i<5 is true because 2<5 is true. So Iteration 2 will be printed.
Third iteration:
Now i++ will be executed.So value of i will be increment by 1 and new value is 3. Now condition will be checked. i<5 is true because 3<5 is true. So Iteration 3 will be printed.

Fourth iteration:
Now i++ will be executed.So value of i will be increment by 1 and new value is 4. Now condition will be checked. i<5 is true because 4<5 is true. So Iteration 4 will be printed.

Fifth iteration:
Now i++ will be executed.So value of i will be increment by 1 and new value is 5. Now condition will be checked. i<5 is false because 5<5 is false.Hence condition is false, iteration of loop will be terminated and rest of the statements followed by } will be executed. In our case return 0; will be executed.

NOTE:

Initialization part of for loop will be executed only for first iteration then condition part. Rest of iteration will be executed as increment or decrement then condition. Another important think is loop will be terminated if condition will turn into false.

for(i=0;i<5; i--)

This for loop will never terminate. Here at first i is initialized by 0, condition is true because 0<5 is true. Then value of i will be decreased by 1 in each next iteration. So update value of next iteration will be less than 5 that means i<5 is always true. This is called infinite for loop. It will cause an abnormal error. It is not mandatory to write initialization, condition and increment or decrement parts inside for(). But semicolon are mandatory.

for(;;) is valid.

but

for() is not valid

Next Previous