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:
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 withkfree seats side by side. The counterin_a_rowgrows at each free seat and drops back to 0 at a taken one. When it reachesk, the row is found: the same linear search, only across two dimensions.maindraws 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.