Skip to content
FollowtheDamnCode

2D Arrays

Rows and columns, like a table.

5 minute read

Big idea

A 2D array is a grid — rows and columns. You use two indices: grid[row][col].

The idea

int seats[3][4] = {
    {1, 0, 0, 1},
    {1, 1, 0, 0},
    {0, 0, 1, 1}
};
  • [3] rows, [4] columns — 12 ints in total.
  • seats[1][2] is row 1, column 2 (both counting from 0) — here 0.

In memory, C stores it row after row in one long line: row 0's four values, then row 1's, then row 2's.

Two loops for two dimensions

The outer loop picks the row, the inner loop walks along it:

Print a multiplication grid
#include <stdio.h>

int main(void) {
    int table[4][5];
    for (int r = 0; r < 4; r++) {
        for (int c = 0; c < 5; c++) {
            table[r][c] = (r + 1) * (c + 1);
        }
    }
    for (int r = 0; r < 4; r++) {
        for (int c = 0; c < 5; c++) {
            printf("%3d", table[r][c]);
        }
        printf("\n");
    }
    return 0;
}
output
  1  2  3  4  5
  2  4  6  8 10
  3  6  9 12 15
  4  8 12 16 20

Run and edit it in the app.

%3d pads each number to 3 characters wide, so the columns line up.

Totals by row and column

Predict: row sums
#include <stdio.h>

int main(void) {
    int m[2][3] = {{1, 2, 3}, {4, 5, 6}};
    for (int r = 0; r < 2; r++) {
        int sum = 0;
        for (int c = 0; c < 3; c++) {
            sum += m[r][c];
        }
        printf("row %d: %d\n", r, sum);
    }
    return 0;
}
What does it print? Show the answer
row 0: 6
row 1: 15

Run and edit it in the app.

Swap the loops (columns outside, rows inside) and you get column sums instead.

Watch it

Common mistake

Mixing up the order: it's [row][col], like reading a book — down to the line, then along it. m[2][0] in a 2 × 3 array is out of bounds, because row 2 doesn't exist.

Think of it like

A cinema: "row F, seat 12". The row gets you to the right line of seats; the seat number gets you to the chair.

🕷️ Spidey-sense: The city is a grid — street and avenue. city[34][5] and I'm at the Empire State. city[5][34] and I'm in the river.

Key terms

  • 2D array — An array of arrays: rows and columns.
  • Row-major order — Storing a 2D array row after row in memory, as C does.
  • Nested loop — A loop inside another loop.

Check yourself

int g[3][4]; how many ints does it hold?

g[1][2] is…

How does C store a 2D array in memory?