C For Loop
When you know exactly how many times you want to repeat something, the for loop is the cleanest choice. It packs the counter setup, the condition, and the update into a single line.
The for Loop
A for loop has three parts separated by semicolons: the initialization (runs once at the start), the condition (checked before each pass), and the update (runs after each pass). Keeping all three together makes counting loops easy to read.
A simple for loop
#include <stdio.h>
int main() {
for (int i = 0; i < 5; i++) {
printf("i is %d\n", i);
}
return 0;
}This prints 0 through 4. First i is set to 0. Before each pass the condition i < 5 is checked. After each pass i++ increases i by 1. The loop stops once i reaches 5.
- Statement 1 sets the starting value and runs only once.
- Statement 2 is the condition that must be true to keep looping.
- Statement 3 updates the counter after every pass.
Counting even numbers up to 10
#include <stdio.h>
int main() {
for (int i = 0; i <= 10; i += 2) {
printf("%d is even\n", i);
}
return 0;
}By using i += 2, the counter jumps 0, 2, 4, 6, 8, 10. This prints every even number from 0 to 10, showing how flexible the update step can be.
Exercise: C For Loop
What are the three parts inside a for loop's parentheses, separated by semicolons?