AP Computer Science A • Unit 4.12

2D Array Traversals

Detailed answer explanations for the Unit 4.12 multiple-choice practice questions.

Q1B
Q2C
Q3A
Q4A
Q5C
Q6C
Q7B
Q8B
Q9B
Q10B
Q11A
Q12C
Q13C
How to use this page: First try each question without looking at the explanation. Then compare your answer with the key and read why the other choices are not correct.

Answer Explanations

Q1

Which nested loop order is row-major for rectangular grid?

AOuter loop over rows, inner loop over rows
BOuter loop over rows, inner loop over columns
COuter loop over columns, inner loop over columns
DOuter loop over columns, inner loop over rows
Correct answer: B. Row-major traversal goes across one row before moving to the next row, so the outer loop chooses the row and the inner loop walks the columns of that row.
Explanation

A 2D array is an array of rows, so a full traversal needs a loop inside another loop. One loop chooses a row and the other visits the values in that row. In row-major order all columns of one row are completed before the next row begins.

  • A is not correct: Both loops would control the row index, so no loop ever varies the column and the separate values inside a row are never reached.
  • C is not correct: Both loops would control the column index, so the row index never changes and the traversal never moves down to the other rows.
  • D is not correct: Putting columns on the outside and rows on the inside is the column-major pattern, which completes all rows in one column before the next column.
Q2

Which condition visits every valid row index of grid?

Ar < grid[0].length
Br <= grid.length
Cr < grid.length
Dr <= grid[0].length
Correct answer: C. The valid rows are 0 through a.length - 1, and r < grid.length is exactly the condition that stops after the last of those.
Explanation

The two length expressions must be kept separate. a.length is the number of rows and a[0].length is the number of columns. The row loop therefore compares against the row count with a strict less-than.

  • A is not correct: This compares the row index against the column count, which is a different number whenever the array is not square, so rows can be missed or overrun.
  • B is not correct: Using <= with the row count runs one row too far, past the last valid row index of a.length - 1.
  • D is not correct: This has both faults at once: it uses the column count as the row bound and the <= comparison that goes one step too far.
Q3

Which assignment replaces the cell at row r, column c with zero?

Agrid[r][c] = 0;
Bgrid[c][r] = 0;
Cc = 0;
Dgrid[r] = 0;
Correct answer: A. An indexed assignment such as grid[r][c] = 0; names the actual array cell at row r and column c, so the stored value is replaced.
Explanation

Algorithms that must replace stored values need row and column indexes. The correct access form is a[row][col], with the row index first and the column index second.

  • B is not correct: The indexes are swapped, so this names the cell at row c and column r, and it can throw an ArrayIndexOutOfBoundsException when the row and column counts differ.
  • C is not correct: This writes to a loop variable rather than to a cell, and changing a variable that holds a copy does not change what the array stores.
  • D is not correct: A single index selects a whole row, which is an int[], so this does not name the one cell in column c.
Q4

In a row-major traversal, when does the inner loop complete?

AFor each single iteration of the outer loop
BOnly once for the entire program
CBefore the outer loop starts
DAfter the outer loop has finished
Correct answer: A. The inner loop runs from start to finish once for every single pass of the outer loop.
Explanation

In row-major traversal the outer loop picks a row and the inner loop completes all columns in that row before the outer loop moves to the next row. That is why the total number of elements visited in a full traversal is rows * cols.

  • B is not correct: If the inner loop finished only once, only the columns of a single row would ever be visited and the remaining rows would be skipped.
  • C is not correct: The inner loop is nested inside the outer loop, so it cannot do its work before the outer loop has chosen a row to work on.
  • D is not correct: Once the outer loop has finished there is no row left to select, and no columns would be visited at all.
Q5

A loop visits columns 0 through 3 in each of 3 rows. How many cells does it visit?

A3
B7
C12
D15
Correct answer: C. Columns 0 through 3 are four columns, and four columns in each of three rows is rows * cols, or 12 cells.
Explanation

A full traversal of a rectangular array visits every combination of a row with a column, so the count is the number of rows multiplied by the number of columns. Counting the columns correctly means remembering that the valid column indexes run from 0 through a[0].length - 1.

  • A is not correct: This counts only the rows, as if each row contributed a single cell instead of one cell per column.
  • B is not correct: This adds the three rows to the four columns instead of multiplying them, which is not how a full traversal is counted.
  • D is not correct: This treats the columns numbered 0 through 3 as five columns, an off-by-one count of the column range.
Q6

Which access uses row r and column c?

Agrid[c][r]
Bgrid[r + c]
Cgrid[r][c]
Dgrid[r, c]
Correct answer: C. The correct access is a[row][col], so row r and column c are written as grid[r][c].
Explanation

The first index selects a row of the array of rows, and the second index selects a value inside that row. Keeping that order is what makes the row and column meanings match the loop variables.

  • A is not correct: The indexes are swapped, which can produce the wrong order and can throw an ArrayIndexOutOfBoundsException when the row and column counts differ.
  • B is not correct: Adding the two indexes leaves a single index, and a single index selects a whole row rather than one value inside a row.
  • D is not correct: The section's cell access always gives each index its own pair of brackets, as in a[row][col], so this form does not select a cell.
Q7

Which error can make a traversal of a non-square array go outside its valid indexes?

AInitializing an accumulator before the loops
BUsing the row count as the column bound
CReading a cell with grid[r][c]
DIncrementing both loop variables
Correct answer: B. Using the row count as the column bound is the error the section warns about, because a.length counts rows, not columns, and can produce an invalid column index.
Explanation

For the rectangular arrays in this course the inner column loop must use a[0].length. When the row and column counts differ, comparing the column index against the row count lets the index run past the last valid column, which is a[0].length - 1.

  • A is not correct: Setting an accumulator to a starting value before the loops is the normal pattern shown in the row-major sum method and touches no index.
  • C is not correct: Reading with grid[r][c] is the correct access form, with the row index first and the column index second.
  • D is not correct: Each loop advances its own variable in the standard nested template, and ordinary loop updates are not what pushes an index outside the valid range.
Q8

Which nested enhanced for header correctly starts a traversal of int[][] grid?

Afor (int row : grid)
Bfor (int[] row : grid)
Cfor (int[][] row : grid)
Dfor (double[] row : grid)
Correct answer: B. Each element of an int[][] is a row, so the outer enhanced-for variable must have the row type int[].
Explanation

Every loop variable must match the type it receives. For a 2D array of integers the outer variable is a 1D row array and the inner variable is a single int taken from that row.

  • A is not correct: This gives the outer variable the type of a single element inside a row, but the outer loop hands it a whole row array instead.
  • C is not correct: This is the type of the entire 2D array, while the outer loop supplies one of its elements, which is a single row.
  • D is not correct: The rows of an int[][] hold integers, so a row variable declared with a different element type does not match what the loop receives.
Q9

Consider the following code segment. What is printed?

int[][] a = { {2, 4}, {6, 8}, {1, 3} };

for (int col = 0; col < a[0].length; col++) {
    for (int row = 0; row < a.length; row++) {
        System.out.print(a[row][col] + " ");
    }
}
A2 4 6 8 1 3
B2 6 1 4 8 3
C2 4 1 3 6 8
D1 3 6 8 2 4
Correct answer: B. The column loop is on the outside, so this is a column-major traversal that prints each column top to bottom before moving on.
Explanation

Column-major traversal reverses the nesting of the row-major template. For each column the inner loop runs through every row, so column 0 gives 2, 6, 1, and then column 1 gives 4, 8, 3.

  • A is not correct: This is row-major order, which prints both values of one row together, but here the outer loop advances the column, not the row.
  • C is not correct: This keeps two values of one row side by side and reorders the rows, which no traversal in this code produces.
  • D is not correct: This starts from the last row, but both loop variables begin at 0, so the first value printed is a[0][0].
Q10

A programmer wants to visit every cell of a rectangular array one column at a time. Which pair of bounds correctly completes the headers?

for (int col = 0; col < ___; col++) {
    for (int row = 0; row < ___; row++) {
        System.out.print(a[row][col]);
    }
}
Aa.length and then a[0].length
Ba[0].length and then a.length
Ca.length and then a.length
Da[0].length and then a[0].length
Correct answer: B. Visiting one column at a time means the outer loop counts columns with a[0].length and the inner loop counts rows with a.length.
Explanation

The two length expressions stay tied to their own index. a[0].length is the number of columns and a.length is the number of rows, so column-major nesting puts the column count on the outer header and the row count on the inner header.

  • A is not correct: This attaches each bound to the wrong variable, giving the column loop the row count and the row loop the column count.
  • C is not correct: Using the row count for both headers puts the row count on the column loop, the error that can produce an invalid column index.
  • D is not correct: Using the column count for both headers makes the row loop stop at the number of columns, which is a different number unless the array is square.
Q11

Consider the following code segment. What is printed?

int[][] a = { {1, 2, 3}, {4, 5, 6} };
int total = 0;
for (int r = 0; r < a.length; r++) {
    for (int c = 0; c < a[0].length - 1; c++) {
        total += a[r][c];
    }
}
System.out.println(total);
A12
B21
C9
D16
Correct answer: A. The inner bound is a[0].length - 1, so c takes only 0 and 1 and the last column is skipped in every row.
Explanation

This is the same pattern as the traced example where the inner loop stops one column early. Row 0 contributes 1+2, row 1 contributes 4+5, and the total is 12.

  • B is not correct: This is the sum of all six values, which is what a full traversal with the bound a[0].length would produce.
  • C is not correct: This is the contribution of the second row alone, as if the outer loop had run for only one row.
  • D is not correct: This drops the first column instead of the last one, but the column loop starts at 0 and stops early at the far end.
Q12

Consider the following code segment, in which a is a square array. What is printed?

int[][] a = { {2,5,8}, {1,4,7}, {6,3,9} };

for (int i = 0; i < a.length; i++) {
    System.out.print(a[i][a.length - 1 - i] + " ");
}
A2 4 9
B5 4 3
C8 4 6
D6 4 8
Correct answer: C. The column index is a.length - 1 - i, so as i moves down the rows the column moves backward from the last column to the first.
Explanation

This is a custom traversal that visits a subset of the grid rather than the whole array. One loop variable drives both indexes, but the column expression runs in reverse, giving a[0][2], a[1][1], and a[2][0].

  • A is not correct: These are the main diagonal values that a[i][i] would print, where the same index is used for both the row and the column.
  • B is not correct: These come from a single fixed column, but the column expression here changes on every pass of the loop.
  • D is not correct: These are the same three values read from the last row back to the first, yet i starts at 0, so the top row prints first.
Q13

Consider the following code segment. What is printed?

int[][] a = { {-2, 5}, {3, -1} };
for (int r = 0; r < a.length; r++) {
    for (int c = 0; c < a[0].length; c++) {
        if (a[r][c] < 0) {
            a[r][c] = 0;
        }
    }
}
System.out.println(a[0][0] + " " + a[1][1]);
A-2 -1
B5 3
C0 0
D2 1
Correct answer: C. The loop uses indexes to assign, so every negative cell is actually replaced by 0, and both printed cells held negative values.
Explanation

An indexed assignment names the real array cell, which is why the stored values change here. a[0][0] was -2 and a[1][1] was -1, so both become 0 before the print statement runs.

  • A is not correct: These are the values before the traversal, but the indexed assignment replaced them, unlike an update to an enhanced-for variable.
  • B is not correct: These are the values in the other two cells, and the print statement asks for a[0][0] and a[1][1].
  • D is not correct: The assignment stores 0 in a negative cell rather than keeping the size of the number without its sign.