In Java, after `int[][] m = new int[3][5];`, what are the values of m.length and m[0].length?
A15 and 5
B3 and 5
C5 and 3
D3 and 15
m is an array of 3 rows, so m.length is 3. Each row is an int array of length 5, so m[0].length is 5. The total element count, 15, is not stored in either field.
Question 2 Multiple Choice
What does this Python code print?
grid = [[0] * 3] * 2
grid[0][0] = 7
print(grid)
A[[7, 0, 0], [0, 0, 0]]
B[[7, 0, 0], [7, 0, 0]]
C[[7, 7, 7], [0, 0, 0]]
DAn IndexError
The outer * 2 copies a reference to the same inner list, so both rows are one list object. Changing grid[0][0] changes what grid[1][0] shows too. A list comprehension such as [[0] * 3 for _ in range(2)] builds two separate rows.
Question 3 True / False
In a row-major traversal of a 2D array, the outer loop runs over the columns and the inner loop runs over the rows.
TTrue
FFalse
Answer: False
Row-major order visits all of row 0, then all of row 1, and so on. The outer loop picks the row and the inner loop moves across that row's columns. Swapping the loops gives column-major order.
Question 4 Short Answer
Write a Java loop (or describe one precisely) that computes the sum of column 2 of a rectangular int[][] array named grid.
Think about your answer, then reveal below.
Model answer: int sum = 0; for (int r = 0; r < grid.length; r++) { sum += grid[r][2]; } A single loop over the rows is enough, because the column index stays fixed at 2.
Processing one column means the row index changes and the column index is constant. A nested loop is not needed. The loop bound is grid.length, the number of rows.