The for loop in C is an entry-controlled loop that provides a concise loop control structure. It gives you the power to control how much time a code you want to execute.
How many times for loop will be executed, that is decided by the three parameters of the “for” loop which is initialization value, test expression/conditions, and increment/decrement statement.
Syntax of for Loop in C
for(initialization; test Expression; increment/decrement)
{
Body of Loop
}
If we explain the above for loop expression.
initialization: this allows you to initialize the initial value for the loop control.
test expression: This is for testing the condition. If the condition satisfies enter into the for loop body and execute the code of for loop.
increment/decrement: This is for increments or decrements of the value of the variable each time after the execution of the for loop body.
The test expression is also known as condition evaluation. Each time the first condition is evaluated the body of for loop is executed and at last, the value of the variable will be incremented.
We can increment the value by one, two, or any as per logic, and also we can decrease the value of the variable after the execution of the for loop body.
Below are examples of for loop in c which will help you to understand the for loop in a better way.
Example 1: C Program to print numbers using for loop
#include <stdio.h>
int main() {
int i;
for (i = 1; i <= 5; i++) {
printf("%d\n", i);
}
return 0;
}
Output
1
2
3
4
5
Example 2: C Program to print natural no. in reverse order
#include <stdio.h>
int main() {
int i;
for (i = 10; i >0; i--) {
printf("%d\n", i);
}
return 0;
}
Output
10
9
8
7
6
5
4
3
2
1