C/C++ Arena

Step 6 of 7

2D arrays

A 2D array is an array of arrays: a grid with rows and columns. It's the natural fit for boards, maps, images and tables.

#include <stdio.h>

int main(void) {
    int seats[2][4] = {
        {1, 0, 1, 1},
        {0, 0, 1, 0},
    };
    int taken = 0;
    for (int r = 0; r < 2; r++) {
        for (int c = 0; c < 4; c++) {
            taken += seats[r][c];
        }
    }
    printf("row 1, seat 2: %d\n", seats[1][2]);
    printf("%d seats taken\n", taken);
    return 0;
}
row 1, seat 2: 1
4 seats taken

Indexing

seats[r][c] means row r, column c. Both start at 0. int seats[2][4] has 2 rows of 4 columns.

In memory

The grid is stored row by row in one long line: all of row 0, then all of row 1. That's why the column count must be known: to find seats[1][2], C skips one full row of 4 and then 2 more elements.

Nested loops

Rows go in the outer loop and columns in the inner loop, so the program walks the grid the same way it's laid out in memory. To compute something per row (like each row's sum), reset the running total at the start of each outer pass and print it at the end of the pass. Something that follows a diagonal needs only one loop: the main diagonal is where row equals column, g[i][i].

Reading a grid from input works the same way: nested loops with scanf("%d", &g[r][c]).

Your turn: read a 3x3 grid of numbers and print the sum of each row on its own line, then the sum of the main diagonal (top-left to bottom-right) as diag N.

Previous: Modify an array in a function Next: Random numbers and shuffling