Thuta Learning
IntermediateProgrammingbeginner

Arrays

Relax. We'll talk through this in plain words — no textbook voice.

An array is a collection that stores multiple values of the same type under one name. Things like five student scores, a list of product prices, or a list of daily temperatures are all great fits for arrays.

c
#include <stdio.h>

int main() {
  int scores[] = {80, 75, 90, 60};
  int total = 0;

  for (int i = 0; i < 4; i++) {
    total += scores[i];
  }

  printf("Total: %d
", total);
  printf("Average: %.2f", total / 4.0);
  return 0;
}

scores[0] is the first item. The loop runs through indexes 0 to 3, adding each score into the total.

You should see
Total: 305 Average: 76.25

Info

Array indexes start at 0. If there are 4 items, the last index is 3.

Easy traps

  • Reading scores[4] means you're reading memory outside the array, which can produce unexpected results. C doesn't always protect you from this mistake.
Arrays | Thuta Learning