AP Computer Science A · Topic 8.2

Traversing 2D Arrays Practice

Part of 2D Array.

Practice questions

36

Want a predicted score for the whole AP CSA exam? Take the 20-question diagnostic and Lumi will plan the rest.

Sample questions

5 of 36 — sign in to practice the rest with adaptive difficulty and mastery tracking.

  1. Sample 1difficulty 2/5

    int[][] m = {{2, 3}, {4, 5}};
    int product = 1;
    for (int[] row : m) {
        for (int x : row) {
            product *= x;
        }
    }
    System.out.println(product);

    What is printed?

    • A

      120

      check_circle
    • B

      60

    • C

      100

    • D

      14

    Why

    2 * 3 * 4 * 5 = 120.

  2. Sample 2difficulty 3/5

    public static int run() {
        int[][] m = {{1,2,3},{4,5,6}};
        int s = 0;
        for (int[] row : m) {
            for (int v : row) {
                if (v % 2 == 1) s += v;
            }
        }
        return s;
    }
    // Call: System.out.println(run());

    What is printed?

    • A

      12

    • B

      21

    • C

      6

    • D

      9

      check_circle

    Why

    Odd values: 1, 3, 5. Sum = 9.

  3. Sample 3difficulty 3/5

    public static int run() {
        int[][] g = new int[3][3];
        for (int i = 0; i < 3; i++)
            for (int j = 0; j < 3; j++)
                g[i][j] = i * 3 + j;
        g[1][1] = g[0][2] + g[2][0];
        return g[1][1];
    }
    // Call: System.out.println(run());

    What is printed?

    • A

      4

    • B

      8

      check_circle
    • C

      10

    • D

      6

    Why

    g[0][2] = 0<em>3+2 = 2. g[2][0] = 2</em>3+0 = 6. g[1][1] = 2 + 6 = 8.

  4. Sample 4difficulty 3/5

    for (int r = 0; r <= grid.length; r++) {
        for (int c = 0; c < grid[0].length; c++) {
            grid[r][c] = 0;
        }
    }

    Which fix corrects the bounds error?

    • A

      Change r <= grid.length to r < grid.length

      check_circle
    • B

      Swap rows and columns

    • C

      Use grid[r-1][c]

    • D

      Change c < grid[0].length to c <= grid[0].length

    Why

    Row indices run 0 to grid.length-1. The outer condition must be r < grid.length to avoid an out-of-bounds access.

  5. Sample 5difficulty 3/5

    public static int sum2D(int[][] g) {
        int total = 0;
        for (int r = 0; r < g.length; r++) {
            for (int c = 0; c < /* missing */; c++) {
                total += g[r][c];
            }
        }
        return total;
    }

    Which expression replaces /* missing */ assuming each row may differ in length?

    • A

      g[c].length

    • B

      g[0].length

    • C

      g.length

    • D

      g[r].length

      check_circle

    Why

    For ragged arrays, use the length of the current row g[r].length. g[0].length only works for rectangular grids.

AP Computer Science A · 8.2 Traversing 2D Arrays — Practice Questions | Acemy