# For Loop

0 test11737865 November 25, 2020

Loop may be defined as a block of the statement which is repeatedly executed for a certain number of times or until a particular condition is satisfied. When an identical task is to be performed for a number of times, then the loopis used.

For example, When we have to print the numbers from 1 to 100. We can use a loop to print the number from 1 to 100.

We have three types of loop.

In this tutorial, We will talk about the For loop.

## For Loop

For loop is useful to execute a statement for a number of times. The syntax of using for loop is

``````for(counter initialization, test condition, increment or decrement)
{
statement; or block of loop
}``````

### The flow of execution of the for loop

The interpreter/compiler takes care of the block of statement to be executed. The different components in for loop are executed in a directed sequence as shown figure.

• At first; the counteris initialized to some value.
• Then the counter variable is tested with the condition.
• If the test is true, the body of the loop is executed
• After finishing the body, the counter variable is incremented or decremented.
• And again updated counter variable is tested with test condition.

The same process is repeated as long as the condition is true. If the result with the test condition is false, the control passes outside the loop i.e. the statement following the loop. See the above figure to understand the flow of for loop.

Let’s look upon one example to make a clear concept on For loop.

``````#include <stdio.h>

int main(){
for(int i=1; i<=10; i++){
// This statement would be executed repeatedly until the condition  i<=10 returns false.
printf("The value of i = %d\n", i);
}
return 0;
}``````

The output of the above program is:

``````The value of i = 1
The value of i = 2
The value of i = 3
The value of i = 4
The value of i = 5
The value of i = 6
The value of i = 7
The value of i = 8
The value of i = 9
The value of i = 10``````

### Infinite for loop:

Infinite for loop means the loop which executes repeatedly and never ends. This is usually happening due to mistakes in the program. When you set the condition that doesn’t return false, then in that condition, we can say infinite loop.

``````#include  <stdio.h>

int main(){
for(int i=1; i>=1; i++){
printf("The value of i = %d\n", i);
}
return 0;
}``````

This is an infinite loop. In this program the condition isi >= 1which is always true for this expression.

Another example of infinite for loop is:

``````for ( ; ; )
{
//block of code
}``````