Arrays and loops
- C course
- Beginner
- Lesson 57/116
- 5 min
Learn to iterate over arrays with for.
Arrays and loops
A for loop is used to print all array elements. The counter serves as the array index.
int scores[5] = {85, 92, 78, 90, 88};
for (int i = 0; i < 5; i++) {
printf("%d\n", scores[i]);
}Here i goes from 0 to 4 and scores[i] accesses each element in turn. The loop bound must be i < 5; writing i <= 5 overflows. Computing the bound with the sizeof idiom is safer.
Computing a sum
You can sum all array elements with a loop. This is the basis for average, max, min and similar computations.
int scores[5] = {85, 92, 78, 90, 88};
int sum = 0;
for (int i = 0; i < 5; i++) {
sum += scores[i];
}
printf("Sum: %d\n", sum); // 433Here sum starts at 0; each iteration adds one element. After the loop sum is 433. For the average, divide by 5.
Practice Print the array with a loop
Write a C program. Declare int scores[5] = {85, 92, 78, 90, 88};. Use a for (int i = 0; i < 5; i++) loop to print each element with printf("%d\n", scores[i]);. Put #include <stdio.h> at the top.
Starter code
#include <stdio.h>
int main(void) {
// Declare scores, print with for
return 0;
}Sample solution
#include <stdio.h>
int main(void) {
int scores[5] = {85, 92, 78, 90, 88};
for (int i = 0; i < 5; i++) {
printf("%d\n", scores[i]);
}
return 0;
}Expected output
85 92 78 90 88
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Complete the loop condition
for (int i = 0; i ____ 5; i++) {
printf("%d", scores[i]);
}
for (int i = 0; i < 5; i++) {
printf("%d", scores[i]);
}
Explanation: i < 5 safely iterates five elements.
2 Match loop and array
| Term | Meaning |
|---|---|
i = 0 |
Init |
i < n |
Condition |
i++ |
Increment |
scores[i] |
Element |
3 What does sum += scores[i] do?
for (int i = 0; i < 5; i++) {
sum += scores[i];
}- Resets sum
- Adds scores[i] to sum Correct answer
- Decrements scores[i]
- Stops the loop
Explanation: sum += scores[i] adds the element to sum.