BETA Try the new lesson view
Code

A two-dimensional array: the cinema hall

When the data is a table (rows and columns), you need a two-dimensional array. The example is a cinema hall: 4 rows of 6 seats, 1 taken, 0 free.

A two-dimensional array

#define ROWS 4
#define SEATS 6

int hall[ROWS][SEATS] = {
    {1, 1, 0, 0, 1, 1},
    {0, 1, 1, 1, 1, 0},
    {0, 0, 0, 1, 0, 0},
    {0, 0, 0, 0, 1, 0},
};

hall[r][s] is seat s of row r, both indexes from 0. hall[2][3] is the fourth seat of the third row (taken). Each row is its own { } block.

In memory a two-dimensional array is its rows one after another:

row 0: hall[0][0]..hall[0][5]4 rows × 6 seatsin memory: one strip, row after row hall[0][…]hall[1][…]hall[2][…]hall[3][…]

So the usual loop has the rows outside and the seats inside:

for (int r = 0; r < ROWS; r++) {
    for (int s = 0; s < SEATS; s++) {
        ... hall[r][s] ...
    }
}

As a parameter

int free_seats(int hall[][SEATS], int row)

The number of rows may be left out ([]), the number of columns may not: to find hall[r][s], the function has to know how many boxes to skip for each row.

There is no const here. With -pedantic a C17 compiler won't let you pass an ordinary two-dimensional array to a const parameter: pointers to arrays with different qualifiers are incompatible in ISO C. For one-dimensional arrays const works as before.

hall.c

CMakeLists.txt gets one more line:

add_executable(p06_hall hall.c)

hall.c:

  • int free_seats(int hall[][SEATS], int row): how many zeros in a row.
  • int find_row(int hall[][SEATS], int k): the first row with k free seats side by side. The counter in_a_row grows at each free seat and drops back to 0 at a taken one. When it reaches k, the row is found: the same linear search, only across two dimensions.
  • main draws the hall (# taken, . free) and looks for 2, 3, 4 and 5 seats side by side.

Run it

Pick p06_hall and ▶:

Row 1: ##..##  free: 2
Row 2: .####.  free: 2
Row 3: ...#..  free: 5
Row 4: ....#.  free: 5
2 seats side by side: row 1.
3 seats side by side: row 3.
4 seats side by side: row 4.
No 5 seats side by side.

The second row has 2 free seats, but not side by side, so only the first row suits two people.

Commit: Add cinema hall.