Loading lessons...
For Loops
For Loops
When you know exactly how many times to repeat, the for loop is the tidy way.
The basic form
for (int i = 0; i < 5; i++) {
printf("%d\n", i);
}
The three parts
A for loop has three sections in its header:
- Start:
int i = 0- sets the starting value. - Condition:
i < 5- checked before each round. - Update:
i++- changes the counter each round.
How it flows
- Run the start once.
- Check the condition; if false, stop.
- Run the body.
- Run the update.
- Back to step 2.
Output
0
1
2
3
4
Counting down
for (int i = 5; i > 0; i--) {
printf("%d\n", i);
}
TL;DR
for (start; condition; update) { ... }.- Start runs once; condition gates each round; update changes each round.
- Perfect when you know the exact count.
- Works in either direction with
i++ori--.