C For Loop
The for loop is ideal when you know in advance how many times you want to repeat something. It combines initialization, condition and increment into one compact line.
for loops are commonly used to iterate over arrays, count up or down, or repeat an action a fixed number of times.
for (init; condition; increment) {
// code
}Anatomy of a for loop
A for loop has three parts separated by semicolons: initialization (runs once), condition (checked each iteration), and increment (runs after each iteration).
Nested for loops
A for loop can contain another for loop inside it, which is common when working with grids or multidimensional data like tables and matrices.
#include <stdio.h>
int main() {
for (int i = 0; i < 3; i++) {
printf("%d\n", i);
}
return 0;
}0
1
2The loop runs three times, printing i and incrementing it each pass.
#include <stdio.h>
int main() {
for (int i = 1; i <= 2; i++) {
for (int j = 1; j <= 2; j++) {
printf("%d,%d ", i, j);
}
}
printf("\n");
return 0;
}1,1 1,2 2,1 2,2 The inner loop runs completely for each iteration of the outer loop.
Key points
- for combines init, condition and increment in one line.
- The loop variable is often scoped to the loop when declared inside it.
- for loops can be nested for multidimensional tasks.
- Any of the three for clauses can be left empty if not needed.
