Counting loops are so common that C has a special, compact loop for them: for.
#include <stdio.h>
int main() {
for (int i = 1; i <= 5; i++) {
printf("%d\n", i);
}
return 0;
}Output
1 2 3 4 5
The brackets hold three parts, separated by ;:
| Part | Here | Meaning |
|---|---|---|
| Start | int i = 1 | Runs once, before the loop begins. |
| Condition | i <= 5 | Checked before every round. False = stop. |
| Step | i++ | Runs after every round. |
Tip:
iis the traditional name for a loop counter. It stands for index.
Counting down and in steps
#include <stdio.h>
int main() {
for (int i = 5; i >= 1; i--) {
printf("%d ", i);
}
printf("Lift off!\n");
for (int i = 0; i <= 20; i += 5) {
printf("%d ", i);
}
printf("\n");
return 0;
}Output
5 4 3 2 1 Lift off! 0 5 10 15 20
Adding things up
A very common pattern: make a total variable before the loop, and add to it inside:
#include <stdio.h>
int main() {
int total = 0;
for (int i = 1; i <= 100; i++) {
total += i;
}
printf("1 + 2 + ... + 100 = %d\n", total);
return 0;
}Output
1 + 2 + ... + 100 = 5050
Repeating something n times
#include <stdio.h>
int main() {
int n;
scanf("%d", &n);
for (int i = 1; i <= 10; i++) {
printf("%d x %d = %d\n", n, i, n * i);
}
return 0;
}Input (what the user types)
7
Output
7 x 1 = 7 7 x 2 = 14 7 x 3 = 21 7 x 4 = 28 7 x 5 = 35 7 x 6 = 42 7 x 7 = 49 7 x 8 = 56 7 x 9 = 63 7 x 10 = 70
Remember: Use
forwhen you know how many times to repeat, andwhilewhen you don't.