Learn/C/7. Arrays
Lesson 7 of 15
Sign in

C, lesson 7

Arrays

Most programs work with lists of things: the scores of a match, the temperatures of a week, the items in a basket. C's built-in collection is the array: a fixed number of values of one type, stored side by side in memory.

Elements are numbered from 0. scores[0] is 72 and scores[4] is 81. You read and write them with square brackets:

Initializing

If you list fewer values than the size, the rest become zero. That makes = {0} the usual way to start with an all-zero array. You can also leave the size out and let the compiler count:

Looping over an array

A for loop from 0 to size - 1 visits every element. sizeof gives the size of the whole array in bytes, so dividing by the size of one element gives the number of elements:

2 exercises to try what you just read.

Exercise 1

Above average

Press Ctrl Enter or Check to test your code.

Exercise 2

Dice tally

Press Ctrl Enter or Check to test your code.

That trick only works on a real array in the same function. Once you pass an array to a function, it decays into a pointer to its first element and the size is lost, so always pass the length alongside:

const promises the function won't modify the array.

No bounds checking

C does not check that an index is valid. Reading scores[5] from a five-element array compiles and runs, but it reads whatever memory happens to sit after the array. That is undefined behaviour and a famous source of security bugs. Keep every index between 0 and size - 1, and when you read data into an array, never store more items than it can hold.

Arrays as lookup tables

C has no built-in dictionary type, but when the keys are small integers an array works as one: the index is the key and the element is the value. Counting is the classic use:

For keys that are characters, subtract a base: letters[c - 'a']++ maps 'a' to 0 and 'z' to 25. You will build a real key-value table with text keys in the lesson on maps and sets.

Two dimensions

An array can hold arrays. int grid[3][4] is three rows of four integers, accessed as grid[row][col]. Nested loops visit every cell.

Further reading

  • cppreference: Array declaration
  • cppreference: Array initialization
  • GNU C Manual: Arrays

Read a count n (1 to 100) followed by n integer scores. Print the average with two digits after the point, then every score that is strictly above the average, in the original order, separated by single spaces. If no score is above the average, print none on the second line.

Read dice rolls (whole numbers from 1 to 6) until the input ends. Ignore any number outside that range. Then print how many times each face came up, from 1 to 6, followed by the most common face. If several faces tie, report the smallest one. If there were no valid rolls, the most common face is 0.

int scores[5] = {72, 88, 95, 60, 81};
scores[3] = 65;                    // replace 60
printf("First: %d\n", scores[0]);
int counts[10] = {0};              // ten zeros
double prices[] = {1.5, 2.25, 4.0}; // size 3
int days[12] = {[1] = 28};         // designated initializer: only index 1 set, rest 0
constexpr int count = sizeof prices / sizeof prices[0];   // 3
double total = 0.0;
for (int i = 0; i < count; i++) {
    total += prices[i];
}
int highest(const int values[], int n) {
    int best = values[0];
    for (int i = 1; i < n; i++) {
        if (values[i] > best) {
            best = values[i];
        }
    }
    return best;
}
int votes[4] = {0};        // candidates 1..3, index 0 unused
int choice;
while (scanf("%d", &choice) == 1) {
    if (choice >= 1 && choice <= 3) {
        votes[choice]++;
    }
}
Input:
5
72 88 95 60 81
Output:
Average: 79.20
Above: 88 95 81
Input:
3 6 6 1 3 6
Output:
1: 1
2: 0
3: 2
4: 0
5: 0
6: 3
Most common: 6