C For Loop
When you know how many times to repeat, the for loop is the clearest choice. It puts the three parts of a counting loop, the start, the condition and the step, on one line.
Syntax
for (start; condition; step) {
// code to repeat
}The start runs once. Before each round the condition is checked; if it is false the loop ends. After each round the step runs.
#include <stdio.h>
int main(void) {
for (int i = 1; i <= 5; i++) {
printf("Round %d\n", i);
}
return 0;
}Round 1 Round 2 Round 3 Round 4 Round 5
The variable i declared in the loop exists only inside the loop. (Declaring it inside the for brackets needs C99 or later; very old code declares int i; before the loop.)
Counting in other steps
The step can be anything: i += 2 counts in twos, i-- counts down.
#include <stdio.h>
int main(void) {
for (int i = 0; i <= 10; i += 2) {
printf("%d ", i);
}
printf("\n");
for (int i = 5; i >= 1; i--) {
printf("%d ", i);
}
printf("\n");
return 0;
}0 2 4 6 8 10 5 4 3 2 1
A multiplication table
#include <stdio.h>
int main(void) {
int n = 7;
for (int i = 1; i <= 10; i++) {
printf("%d x %2d = %2d\n", n, i, n * i);
}
return 0;
}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
Nested loops
A loop inside a loop runs completely for each round of the outer loop. This prints patterns and tables:
#include <stdio.h>
int main(void) {
for (int row = 1; row <= 4; row++) {
for (int col = 1; col <= row; col++) {
printf("*");
}
printf("\n");
}
return 0;
}* ** *** ****
Off-by-one errors
The most common loop bug is running one time too many or too few. for (int i = 0; i < 5; i++) runs 5 times with i from 0 to 4, which is exactly what you need for an array of 5 elements. i <= 5 would run 6 times. Count the rounds on paper when unsure.
Practice exercises
- Print the multiplication table of a number the user types.
- Add up the numbers from 1 to 100 and print the total.
- Print the triangle of stars upside down, from 4 stars down to 1.
- Print a 5 by 5 square of
#characters with nested loops.