Two-Dimensional Arrays
Some data forms a table with rows and columns: the seats in a cinema, a chessboard, a school timetable. For such data, C has two-dimensional arrays, arrays with two sizes:
int seats[3][4] = {
{1, 1, 0, 0},
{0, 1, 1, 1},
{0, 0, 0, 1}
};This array is a small cinema with 3 rows of 4 seats: 1 means that the seat is taken, 0 that it's free. The first number in square brackets is the number of rows, the second one the number of columns. In the curly braces, each row has its own pair of braces, and a comma separates it from the next row. You don't have to write each row on its own line, but it makes the table easy to see.
An element has two indexes: the row first, then the column, both counted from 0. seats[1][2] is the element in the second row (index 1) and the third column (index 2). You read and change it like any other element:
printf("%d\n", seats[1][2]);
seats[2][0] = 1;
printf("%d\n", seats[2][0]);This prints:
1
1To go through the whole table, you need two nested loops. The outer one goes through the rows, and for each row, the inner one goes through its columns. You know this from the lesson on loops, where nested loops printed rows and columns:
const int ROWS = 3;
const int COLS = 4;
for (int row = 0; row < ROWS; row++) {
for (int col = 0; col < COLS; col++) {
printf("%d ", seats[row][col]);
}
printf("\n");
}After the change above, this prints:
1 1 0 0
0 1 1 1
1 0 0 1 For each row, the inner loop prints its four seats on one line, and the printf("\n") after the inner loop ends the line. Then the outer loop moves on to the next row. The names row and col (column) make it clear which index is which. With i and j, they are easy to mix up.
An index past the end is a mistake here too: seats[3][0] doesn't compile (error: array index 3 is past the end of the array (that has type 'int[3][4]')), and a loop with row <= ROWS stops with RuntimeError: unreachable.
Instructions
- 1
A customer has bought the second seat in the third row. Below the output line, write a statement that changes this element of
seatsto1. - 2
Print the whole cinema with two nested loops, one row on each line, with the seats separated by spaces:
1 1 0 0 0 1 1 1 0 1 0 1 - 3
Count the free seats: create a variable
free_seatswith the value0, go through the cinema with two nested loops again, and increasefree_seatsfor every0. After the loops, print the result asFree seats: 5.