Introduction
It does the same thing as the while loop. It means, the for loop can be used to execute a group of statements repeatedly depending upon the number of elements in a sequence
Syntax :
Example of for loop in C :
Printing numbers from 0 to 10 :
0
1
2
3
4
5
6
7
8
9
10
Breakdown of the Code :
for (int i = 0; i <= 10; i++)
Here we declared the for loop and and an integer i . Initially i is 0. Then we stated the for loop should execute the codes if i remains less than or equal to 10. The we stated to increment i to avoid an infinite loop.
{
printf("%d\n", i);
}
Code inside the loop states to print the variable i through each iteration.
Some Examples :
Print the even numbers from 1 to 10 using a for loop.
2
4
6
8
10
Display numbers from 5 to 1 in descending order.
5
4
3
2
1
Note the we stated the condition as “as long as i is greater than or equal to 1” as we decremented i for each iteration.
Hope you enjoyed this blog
Have any doubt ?
DM me on Instagram
Peace ✌️