C Arrays
An array is a row of values under one name. One name now holds a whole set of scores instead of one variable per score.
Read one value
The row holds 10, 20, 30, 40, and index 1 picks the second value. The print line shows 20.
#include <stdio.h>
int main() {
int scores[4] = {10, 20, 30, 40};
printf("%d\n", scores[1]);
return 0;
}Change one value
The first slot changes from 10 to 99. The print line shows the new value.
#include <stdio.h>
int main() {
int scores[4] = {10, 20, 30, 40};
scores[0] = 99;
printf("%d\n", scores[0]);
return 0;
}Walk the whole row
i walks from 0 to 3, and each round prints the value at that index. All four values print in order.
#include <stdio.h>
int main() {
int scores[4] = {10, 20, 30, 40};
for (int i = 0; i < 4; i++) {
printf("%d\n", scores[i]);
}
return 0;
}Example
#include <stdio.h>
int main() {
int scores[4] = {10, 20, 30, 40};
int total = 0;
for (int i = 0; i < 4; i++) {
total = total + scores[i];
}
printf("%d\n", total);
return 0;
}Key points
- An array holds many values of one type under one name.
- int scores[4] = {10, 20, 30, 40}; makes a row of four ints named scores.
- The number in brackets says how many values the row holds.
- scores[1] is the second value in the row, because the first value is scores[0].
- An index is the number in brackets after the name.
- scores[0] = 99; puts 99 in the first slot of the row.
- A loop can walk the row one index at a time.
The row holds 10, 20, 30, and 40. A loop adds each value to total, and the print line shows 100.
Note
Only use indexes from 0 to 3 for a row of four values.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
What is scores[1] when scores holds {10, 20, 30, 40}?