AP Computer Science A • Unit 4.13

Implementing 2D Array Algorithms

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

Q1C
Q2C
Q3B
Q4B
Q5C
Q6A
Q7D
Q8C
Q9B
Q10A
Q11C
Q12B
Q13D
Q14B
Q15C
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 algorithm correctly totals every value in int[][] data?

AReset total at the start of each row.
BAdd only data[row][0].
CInitialize once, add each cell, and return after both loops.
DReturn total after the inner loop's first iteration.
Correct answer: C. One accumulator is set up before the loops, every cell is added as it is visited, and the value is returned only after both loops finish.
Explanation

Whole-array work uses two loops, one over a.length and one over a[0].length. A sum cannot be reported until every required cell has been processed, so the return belongs after the traversal.

  • A is not correct: Resetting total at the start of each row throws away everything added in the earlier rows, leaving only the last row counted.
  • B is not correct: Adding only data[row][0] touches the first column of each row and never reaches the remaining columns of the array.
  • D is not correct: Returning inside the inner loop after one iteration is an early exit, and an accumulator has no correct value until all cells are added.
Q2

Which initialization works when every value may be negative?

Aint max = 0;
Bint max = data.length;
Cint max = data[0][0];
Dint max;
Correct answer: C. Starting from data[0][0] begins the search at an actual value stored in the array, so the comparison works even when every value is negative.
Explanation

The section initializes max = a[0][0] and then replaces it whenever a larger cell appears. A fixed guess is only safe if it is known to occur in the data, which it is not.

  • A is not correct: int max = 0; is a fixed guess that may never appear in the array, and no negative cell can ever exceed it.
  • B is not correct: data.length is the number of rows, not a value stored in the array, so the search starts from an unrelated number.
  • D is not correct: int max; gives the variable no starting value at all, so the method never begins from a value that is actually in the array.
Q3

Which change preserves the fractional part of an average?

AStore the total and result as int.
BUse a double total before dividing by the count.
CReturn before the final row.
DDivide the row count by the column count.
Correct answer: B. Accumulating into a double before dividing by the count keeps the division from discarding the fractional part.
Explanation

The section's average method declares double total = 0; and counts the cells separately, then returns total / count. The type of the accumulator is what decides whether the fraction survives.

  • A is not correct: Holding the total and the result as int is exactly the integer division that throws the fractional part away.
  • C is not correct: Returning before the final row leaves cells unvisited, and an average cannot be reported until every required cell has been added and counted.
  • D is not correct: Dividing the row count by the column count uses only the array's dimensions and ignores the accumulated total entirely.
Q4

A method totals selected row r. Which loop is correct?

Afor (int r = 0; r < a.length; r++)
Bfor (int c = 0; c < a[0].length; c++)
Cfor (int c = 0; c < a.length; c++)
Dfor (int c = 0; c <= a[0].length; c++)
Correct answer: B. The row r is already selected, so the loop must vary the column index and run to the column count a[0].length.
Explanation

A row total holds the row fixed and loops through the columns. Because the array is rectangular, a[row].length equals a[0].length, so the column count is the correct bound.

  • A is not correct: This varies the row, but the row is the dimension the method has already fixed as the selected row r.
  • C is not correct: a.length is the row count being used as a column bound, which can fail on an array that is not square.
  • D is not correct: <= lets c reach a[0].length, one position past the last column, which is an invalid index.
Q5

A method totals selected column c. Which loop is correct?

Afor (int r = 0; r < a[0].length; r++)
Bfor (int c = 0; c < a.length; c++)
Cfor (int r = 0; r < a.length; r++)
Dfor (int r = 0; r <= a.length; r++)
Correct answer: C. The column c is fixed, so the loop varies the row index and is bounded by the row count a.length.
Explanation

A column total is the mirror image of a row total: hold the column fixed and move down the rows. The bound must match the index that changes, which here is the row.

  • A is not correct: a[0].length is the column count, so bounding a row index with it can run past the last row on a non-square array.
  • B is not correct: This varies the column even though the column is the dimension the method has already selected and must keep fixed.
  • D is not correct: <= lets r reach a.length, one row past the last valid row index.
Q6

Where do the returns belong in an any-match search?

AReturn true at a match and false after both loops.
BReturn false after the first nonmatch.
CPlace both returns before the loops.
DReturn true only after every cell is checked.
Correct answer: A. Success is certain at the first cell with the property, but failure is only certain once both loops have finished.
Explanation

Each return belongs where its conclusion becomes certain. If false were returned earlier, an unchecked cell could still satisfy the property and the answer would be wrong.

  • B is not correct: Returning false at the first nonmatch is the all-match pattern, and here an unchecked cell could still satisfy the property.
  • C is not correct: Returns placed before the loops decide the answer without examining a single cell of the array.
  • D is not correct: Delaying true until the whole traversal ends gives up the intentional early exit that the any-match pattern allows at the first match.
Q7

Where should an all-match algorithm return true?

AAfter the first matching cell
BInside the inner loop after each match
CBefore testing any cell
DAfter both loops finish without finding a failure
Correct answer: D. Only after both loops finish with no failing cell is it certain that every cell has the property.
Explanation

The all-match method may return false as soon as one cell fails the test, because a single failure settles the question. The opposite conclusion needs the entire traversal behind it.

  • A is not correct: One matching cell says nothing about the rest, and cells that fail the test may still lie ahead in the traversal.
  • B is not correct: Returning inside the inner loop after each match declares success while unvisited cells could still fail the test.
  • C is not correct: A conclusion reached before any cell is tested does not depend on the array's contents at all.
Q8

Which update counts cells that are multiples of 3?

Aif (count % 3 == 0) { count++; }
Ba[r][c] = count++;
Cif (a[r][c] % 3 == 0) { count++; }
Dif (a[r][c] / 3) { count++; }
Correct answer: C. The test applies the remainder operator to the cell value a[r][c] and increments count only when the cell has the property.
Explanation

A property count checks the current cell inside the nested loops and adds one to the counter each time the test succeeds. The counter itself is never the thing being tested.

  • A is not correct: This tests count rather than the cell, so the values stored in the array never influence the result.
  • B is not correct: This assigns into the array, modifying the cell instead of testing it and tallying the cells that qualify.
  • D is not correct: Division does not report divisibility; the remainder is what shows whether a value is a multiple of 3.
Q9

Consider the following method call. Assume sum adds rows r1 through r2 and columns c1 through c2, inclusive. What is printed?

int[][] m = { {4, 9, 2}, {7, 1, 6}, {3, 8, 5} };
System.out.println(sum(m, 0, 1, 1, 2));
A16
B18
C25
D29
Correct answer: B. The bounds are inclusive, so the selected subgrid is rows 0 and 1 crossed with columns 1 and 2, giving 9 + 2 + 1 + 6.
Explanation

A subgrid sum runs row from r1 to r2 and col from c1 to c2, both with <=. Every cell outside that rectangle, including all of row 2 and all of column 0, is skipped.

  • A is not correct: 16 is short by one of the four selected cells; 9, 2, 1, and 6 all lie inside the bounds.
  • C is not correct: 25 adds a cell from column 0, but the column range begins at c1, which is 1.
  • D is not correct: 29 totals every column of rows 0 and 1, ignoring that column 0 is outside the range.
Q10

Consider the following code segment. What is the final value of count?

int[][] m = { {2, 2, 5}, {7, 7, 7} };
int count = 0;
for (int r = 0; r < m.length; r++) {
    for (int c = 0; c < m[0].length - 1; c++) {
        if (m[r][c] == m[r][c + 1]) {
            count++;
        }
    }
}
A3
B2
C4
D5
Correct answer: A. Row 0 contributes the pair of twos, and row 1 contributes two overlapping pairs of sevens, for three matches in all.
Explanation

The bound m[0].length - 1 stops the column loop one position early so that c + 1 is always valid. With three columns, each row offers exactly two adjacent pairs to test.

  • B is not correct: 2 misses one of the two overlapping equal pairs in the row that holds three sevens.
  • C is not correct: 4 is more matches than the loop even tests, since two rows of three columns give only four comparisons and one of them fails.
  • D is not correct: 5 exceeds the four comparisons the loop makes in total, so it cannot be reached.
Q11

A method compares each cell with the cell directly below it. Which expression completes the outer bound?

for (int r = 0; r < ______; r++) {
    for (int c = 0; c < a[0].length; c++) {
        if (a[r][c] == a[r + 1][c]) {
            count++;
        }
    }
}
Aa.length
Ba[0].length - 1
Ca.length - 1
Da.length + 1
Correct answer: C. Stopping the row loop at a.length - 1 keeps a[r + 1][c] inside the array on every pass.
Explanation

Vertical pairs are the same idea as horizontal pairs with the dimensions exchanged. The - 1 in the bound is what protects the second index of the pair.

  • A is not correct: a.length lets r reach the last row, where a[r + 1][c] names a row that does not exist.
  • B is not correct: a[0].length - 1 is a column count used as a row bound, and swapped dimensions can fail on a non-square array.
  • D is not correct: a.length + 1 runs even further past the last row, making both a[r][c] and a[r + 1][c] unsafe.
Q12

A duplicate search compares a cell at (r,c) with later cells. Why is first set to c + 1 in the same row?

for (int r2 = r; r2 < a.length; r2++) {
    int first = 0;
    if (r2 == r) {
        first = c + 1;
    }
    // scan columns first through the final column
}
ATo skip every cell in later rows
BTo avoid self-comparisons and repeated comparisons
CTo compare only the first column
DTo make the array rectangular
Correct answer: B. Beginning at c + 1 in the current row skips the cell itself and every cell already compared against it.
Explanation

The duplicate search compares each cell only with the cells that come after it. In the same row the second scan starts one column later; in every later row it starts at column 0.

  • A is not correct: Later rows are still scanned in full, because the adjustment to first applies only when r2 equals r.
  • C is not correct: The inner scan continues through the final column, so the comparison is not limited to a single column.
  • D is not correct: Rectangular shape is a property the array already has and that the section assumes, not something a starting index produces.
Q13

Consider the following left shift of row 1. What does row 1 contain afterward?

int[][] a = { {8, 4, 1}, {6, 3, 9} };
for (int c = 0; c < a[0].length - 1; c++) {
    a[1][c] = a[1][c + 1];
}
a[1][a[0].length - 1] = 0;
A{0, 6, 3}
B{9, 6, 3}
C{6, 3, 0}
D{3, 9, 0}
Correct answer: D. Each cell copies the value from the column to its right, so 3 and 9 move left, and the final cell is then set to 0.
Explanation

A left shift copies forward, reading a[r][c + 1] into a[r][c], which overwrites the first value. The discarded endpoint is what leaves the last cell open for the assignment after the loop.

  • A is not correct: {0, 6, 3} places the zero at the front, but a left shift leaves the open cell at the end of the row.
  • B is not correct: {9, 6, 3} wraps the last value around to the front, which is a rotation rather than a shift.
  • C is not correct: {6, 3, 0} keeps the original first value, but the shift overwrites it with the value from the next column.
Q14

Consider the following downward rotation of column 0. What are the values in column 0 afterward?

int[][] a = { {2, 5}, {4, 7}, {9, 1} };
int last = a[a.length - 1][0];
for (int r = a.length - 1; r >= 1; r--) {
    a[r][0] = a[r - 1][0];
}
a[0][0] = last;
A2, 4, 9
B9, 2, 4
C4, 9, 2
D9, 4, 2
Correct answer: B. The saved last value returns to the top and every other value moves down one row, giving 9, 2, 4.
Explanation

A downward movement copies backward, reading a[r - 1][c] into a[r][c] so each source is read before it is overwritten. The bound r >= 1 keeps the - 1 access valid, and the saved endpoint is restored at the opposite end.

  • A is not correct: 2, 4, 9 is the column left untouched, but the loop copies every value down one position.
  • C is not correct: 4, 9, 2 moves the values up the column, the opposite of the direction this loop copies.
  • D is not correct: 9, 4, 2 reverses the column; a rotation moves only the saved endpoint across, leaving the others in their original order.
Q15

Consider the following code segment. What does row 0 contain afterward?

int[][] a = { {3, 8, 1, 6}, {5, 2, 9, 4} };
int left = 0;
int right = a[0].length - 1;
while (left < right) {
    int temp = a[0][left];
    a[0][left] = a[0][right];
    a[0][right] = temp;
    left++;
    right--;
}
A{3, 8, 1, 6}
B{1, 6, 3, 8}
C{6, 1, 8, 3}
D{8, 3, 6, 1}
Correct answer: C. The two pointers swap the outermost pair and then the pair inside it, leaving the row in the opposite order.
Explanation

The reverse pattern holds one row fixed and exchanges a[0][left] with a[0][right] through a temp variable while left < right. With four columns that is two swaps.

  • A is not correct: {3, 8, 1, 6} is the row unchanged, but the loop body runs while left is still less than right.
  • B is not correct: {1, 6, 3, 8} exchanges the two halves as blocks instead of swapping the outer pair and then the inner pair.
  • D is not correct: {8, 3, 6, 1} swaps neighboring cells in place, but the two pointers move toward each other from opposite ends.