Skip to content
FollowtheDamnCode

Arrays

A row of boxes under one name.

6 minute read

Big idea

An array is a row of boxes of the same type, under one name. You reach each box by its index, counting from 0.

The idea

int marks[5] = {72, 85, 90, 64, 78};
  • int — every box holds an int.
  • marks — the one name for the whole row.
  • [5] — five boxes. An array's size is fixed once it's created.

The boxes are numbered 0 to 4 — the first is marks[0], the last is marks[4]. There is no marks[5].

printf("%d\n", marks[0]);  // 72
marks[3] = 70;             // change the fourth box

Watch it

Arrays and loops

Arrays and for loops go together: for (int i = 0; i < n; i++) visits every index exactly once. Here's the classic "find the biggest":

Largest value — change the numbers
#include <stdio.h>

int main(void) {
    int nums[6] = {14, 3, 27, 9, 27, 1};
    int n = 6;
    int best = nums[0];
    for (int i = 1; i < n; i++) {
        if (nums[i] > best) {
            best = nums[i];
        }
    }
    printf("Largest: %d\n", best);
    return 0;
}
output
Largest: 27

Run and edit it in the app.

Start best at the first element, not at 0 — otherwise an array of all-negative numbers would wrongly report 0.

Watch the loop

Common mistake

Reading or writing past the end. C doesn't check — marks[5] or marks[-1] quietly touches whatever memory is next door, which can crash the program or corrupt other variables. The last valid index is always size − 1.

Fix the bug: print all five values, nothing more
#include <stdio.h>

int main(void) {
    int a[5] = {1, 2, 3, 4, 5};
    for (int i = 1; i <= 5; i++) {
        printf("%d ", a[i]);
    }
    printf("\n");
    return 0;
}
output
1 2 3 4 5

Run and edit it in the app.

It skips a[0] and reads a[5] — one box past the end — so the last number printed is whatever happens to live there.

Think of it like

A row of numbered lockers. One corridor name, many lockers — and the first locker is number 0.

🕷️ Spidey-sense: My web-fluid cartridges sit in a row on my belt: cartridge[0] to cartridge[5]. Reaching for cartridge[6] means grabbing my own ribs.

Key terms

  • Array — A fixed-size row of values of one type.
  • Element — One value in the array.
  • Index — An element's position, starting at 0.
  • Out of bounds — Using an index below 0 or at/after the size.

Check yourself

int a[5]; What is the last valid index?

What does C do if you read a[10] from an array of 5?

To find the maximum, start best at…