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 task

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.

Challenge 2

Read a 3x3 grid of numbers. Print the sum of each column on one line, separated by spaces, then the sum of the other diagonal (top-right to bottom-left) as anti N.

Challenge 3

Read the number of rows r and columns c (each at most 10), then an r by c grid. Print the grid transposed: rows become columns. Input:

2 3
1 2 3
4 5 6

prints:

1 4
2 5
3 6

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