A for loop is a pre-tested loop. A for loop statement is used when a user knows how many times you want to execute the code. A for loop statement executes a block of statements repeatedly for the fixed number of times. A for loop is a most popular loop.
Syntax of for loop:
Following is a general syntax to write code using for loop –
1 2 3 4 |
for(initialization; condition; increment or decrement) { //block of code } |
NOTE: It is compulsory to give two semicolons in the pair of round braces () else compiler will give an error.
It is mandatory to give two semicolons(;) whether you write an initialization expression or increment or decrement expression.
Working of for loop:
- The initialization is executed first. It initializes a loop counter only once.
- Next, the condition is evaluated. If the condition is true then statements within the body of the loop are executed.
If a condition is false, the body of the loop is not executed and flow of control jumps to next statement just after the ‘for’ loop. - After executing the body of the loop, flow of control jumps to increment/decrement statement.
- Now the condition is evaluated again. If it is true, the loop executes and the process repeats.
Example:
1 2 3 4 5 6 7 8 |
#include<stdio.h> int main() { for(int i = 1; i < 5; i++) { printf("%d\t", i); } } |
Output:
1 |
1 2 3 4 |
Here also the output is same as while and do-while loop. Firstly, i is initialized by 1, then condition i < 5 is checked and print value of i. Then after i is incremented. Again condition will be check if true then execute printf() statement else it breaks the loop. In this way, a loop is repeated until the condition is false.
Flowchart of for loop:
The flowchart of for loop shown below would help you to understand the operation of for loop.
Forms of for loop:
Following are some valid syntax of for loop:
-
12345int i=1; //initialization is done in the declaration statementfor(; i<= 10; i++){printf("%d\t",i);}
-
123456int i=1;for(; i <= 10; ) //still semicolon is neccessary.{printf("%d\t",i);i++;}
-
1234int i,j;for(i=1,j=2; j <= 10; j++) //multiple initialization in for loop is allowed{}
-
1234for(;;){printf("infinity for loop");}
This loop is called as infinity for loop. Because it executes the number of time.
There is no initialization, no condition, no increment/decrement.
This loop print “infinity for loop” infinite times.