The for loop
- C course
- Beginner
- Lesson 42/116
- 4 min
Learn to write counted loops with for and use a counter.
The for loop
The for loop is used to iterate a fixed number of times. It has three parts: initialization, condition and increment. They're separated by semicolons.
for (int i = 0; i < 5; i++) {
printf("%d\n", i);
}Here i starts at zero, increments by one each iteration, and the loop ends when i reaches 5. i++ means i = i + 1. Output: 0 1 2 3 4 (each on its own line).
Counting down
The counter doesn't have to go up. You can also count down; useful for countdowns or reverse iteration.
for (int i = 3; i > 0; i--) {
printf("%d\n", i);
}
printf("Go!\n");Here i-- decrements by one each iteration. Output: 3 2 1 Go!. Init, condition and increment must agree; otherwise the loop either never runs or runs forever.
Practice Count from 1 to 5
Write a C program. Use a for (int i = 1; i <= 5; i++) loop to print each i with printf("%d\n", i);. Put #include <stdio.h> at the top.
Starter code
#include <stdio.h>
int main(void) {
// Print 1 to 5 with for
return 0;
}Sample solution
#include <stdio.h>
int main(void) {
for (int i = 1; i <= 5; i++) {
printf("%d\n", i);
}
return 0;
}Expected output
1 2 3 4 5
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 How many times does for (int i=0; i<3; i++) run?
for (int i = 0; i < 3; i++) {
printf("%d", i);
}- 2 times
- 4 times
- 3 times Correct answer
- Infinite
Explanation: Three iterations for i=0,1,2.
2 Write the increment
for (int i = 0; i < 5; ____) {
printf("%d", i);
}
for (int i = 0; i < 5; i++) {
printf("%d", i);
}
Explanation: i++ increments by one each iteration.
3 Match the for parts
| Term | Meaning |
|---|---|
int i = 0 |
Init |
i < 5 |
Condition |
i++ |
Increment |
{ } |
Loop body |