An array of arrays: rows and columns. Mark cinema seats and count them with nested loops.
Java · beginner · 8 min · 23 steps · free
public class TwoDArraysDemo {
public static void main(String[] args) {
int[][] seats = new int[2][3];
seats[0][1] = 1;
seats[1][2] = 1;
int taken = 0;
for (int row = 0; row < seats.length; row++) {
for (int col = 0; col < seats[row].length; col++) {
taken += seats[row][col];
}
}
System.out.println("Seats taken: " + taken);
}
}new int[2][3] makes 2 rows of 3 seats. In memory it is one array holding two row arrays.taken is created on the stack with the value 0.seats.length is the number of rows: 2.seats[row].length is the number of columns in this row: 3.taken += seats[row][col].col changes from 0 to 1.taken changes from 0 to 1.col changes from 1 to 2.taken += seats[row][col].col goes out of scope and disappears.row changes from 0 to 1.col is created on the stack with the value 0.taken += seats[row][col].col changes from 0 to 1.taken += seats[row][col].col changes from 1 to 2.taken changes from 1 to 2.col goes out of scope and disappears.row goes out of scope and disappears.Seats taken: 2.Answer: 3. The outer array has 3 rows.
Answer: Row 1, column 2. Row first, then column.
← Arrays · StringBuilder: Changeable Text →