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

2. Key Points of the For Loop

3. When to Use the For Loop

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