DMarlon Studio

Lesson 10 · 10 of 20

Arrays · C

Store many values of the same type in a C array: a week of temperatures, their average and their maximum, with indexes that start at 0.

C · Arrays in DMarlon Studio: the example's code and its output in the terminal

An array stores several values of the same type, one after another in memory. double temps[7] = {...} makes room for seven double values and gives them their values between braces. days is another array, of seven char.

Each element is reached by its index in square brackets, and indexes start at 0: temps[0] is Monday and temps[6] is Sunday. The number of elements is worked out with sizeof(temps) / sizeof(temps[0]): the total size divided by the size of one. temps[2] = 20.0 changes Wednesday.

A for from 0 to count - 1 goes through the array: it prints each day, adds the temperatures into sum and keeps the highest in max, together with its position in hottest. From that you get the average and the hottest day.

If you give fewer values than the size, the rest start at 0: in votes[4] = {3, 5} options 3 and 4 are 0. Careful: C does not check the limits, and temps[7] would silently read memory that does not belong to the array.

Code · main.c

#include <stdio.h>int main(void) {    // An array keeps several values of the same type, one after another.    double temps[7] = {18.5, 21.0, 19.5, 24.0, 26.5, 22.0, 17.5};    char days[7] = {'M', 'T', 'W', 'T', 'F', 'S', 'S'};    int count = sizeof(temps) / sizeof(temps[0]);  // 7 elements    // Positions start at 0: temps[0] is the first, temps[6] the last.    printf("First: %.1f, last: %.1f\n", temps[0], temps[count - 1]);    temps[2] = 20.0;  // change one element    double sum = 0, max = temps[0];    int hottest = 0;    for (int i = 0; i < count; i++) {        printf("%c %5.1f\n", days[i], temps[i]);        sum += temps[i];        if (temps[i] > max) {            max = temps[i];            hottest = i;        }    }    printf("Average: %.2f\n", sum / count);    printf("Hottest: day %d (%c), %.1f degrees\n", hottest + 1, days[hottest], max);    // Elements without a value start at 0.    int votes[4] = {3, 5};    votes[3] += 2;    for (int i = 0; i < 4; i++) printf("Option %d: %d votes\n", i + 1, votes[i]);    return 0;}

Output · cc main.c -o main && ./main

First: 18.5, last: 17.5
M  18.5
T  21.0
W  20.0
T  24.0
F  26.5
S  22.0
S  17.5
Average: 21.36
Hottest: day 5 (F), 26.5 degrees
Option 1: 3 votes
Option 2: 5 votes
Option 3: 0 votes
Option 4: 2 votes

Key points

  • An array stores several values of the same type.
  • Indexes go from 0 to size - 1.
  • sizeof(a) / sizeof(a[0]) gives the number of elements.
  • Elements without a starting value are 0.
  • C does not check whether an index is outside the array.

Exercise

Add the lowest temperature and its day, and count how many days went above 20 degrees.