C For Loop
The for loop in C is used when you know the number of iterations in advance. It allows you to initialize a loop counter, specify a condition for continuing the loop, and update the counter in a single line, making it a compact loop structure.
1. For Loop Syntax
The for loop executes the code block a specified number of times, based on the initialization, condition, and increment/decrement operations defined in the loop header.
Syntax:
for (initialization; condition; increment/decrement) {
// code to be executed
}
Flowchart of for loop in C

Example:
#include <stdio.h>
int main()
{
for (int i = 0; i < 5; i++) {
printf("%d\n", i);
}
return 0;
}
Output:
0
1
2
3
4
1
2
3
4
2. Key Points of the For Loop
- The for loop is ideal when the number of iterations is known beforehand.
- It allows you to initialize a counter, define the condition, and update the counter in one line.
- If the condition is false from the beginning, the loop body will not execute.
3. When to Use the For Loop
- Use the for loop when you know the number of iterations in advance or when you need to iterate through a range of values in a controlled manner.
- It is especially useful when you need to perform repetitive tasks with a defined number of iterations, such as iterating over an array.
4. Comparison with Other Loops
Feature | For Loop | While Loop | Do-While Loop |
---|---|---|---|
Condition Check | At the beginning of each iteration | At the beginning of each iteration | At the end of each iteration |
Minimum Iterations | Zero or more | Zero or more | At least one |
Use Case | When the number of iterations is known | When the number of iterations is unknown, condition checked before each iteration | When the block must execute at least once, condition checked after each iteration |