Two-Dimensional Arrays

An array holds values in one row. Some data looks more like a table, with rows and columns, like the seats in a cinema or a game board. For this you use a two-dimensional array. You write it with two pairs of square brackets, the number of rows first:

#include <iostream>
using namespace std;

int main() {
    int seats[2][3] = {
        {1, 1, 0},
        {0, 1, 1}
    };
    cout << seats[0][1] << "\n";
    cout << seats[1][0] << "\n";
    return 0;
}

Output:

1
0

int seats[2][3] means 2 rows with 3 columns each. The starting values have one inner pair of braces for each row. Here 1 means the seat is taken and 0 means it is free.

To reach one value, you give two indexes: first the row, then the column. Both start at 0. So seats[0][1] is row 0, column 1, which holds 1. And seats[1][0] is the first seat of the second row, which holds 0.

          col 0  col 1  col 2
 row 0  |   1  |   1  |   0  |
 row 1  |   0  |   1  |   1  |

Visiting every value

To go through the whole table, use the nested loops from the Nested Loops lesson. The outer loop goes through the rows. For each row, the inner loop goes through its columns:

int seats[2][3] = {
    {1, 1, 0},
    {0, 1, 1}
};
seats[0][2] = 1;

for (int row = 0; row < 2; row++) {
    for (int col = 0; col < 3; col++) {
        cout << seats[row][col] << " ";
    }
    cout << "\n";
}

Output:

1 1 1 
0 1 1

seats[0][2] = 1 marks the last seat of row 0 as taken, so the first row now prints 1 1 1. The loop limits, 2 and 3, are the same numbers as in the declaration. The cout << "\n" is inside the outer loop but after the inner loop, so it runs once per row and starts a new line.

Keep the order of the indexes the same as in the declaration: seats[row][col]. If you swap them by mistake and write seats[col][row], the program still compiles, but it reads the wrong values, or values outside the array. Loop variables named row and col make that mistake easier to see than i and j.

The rules from the Arrays lesson apply here too. The size is fixed, and C++ does not check that an index is inside the table. The Two-Dimensional Vectors lesson, later in the course, shows a table whose size can be chosen while the program runs.

In the exercise, read 6 numbers into a table with 2 rows and 3 columns, and print the sum of each row.