Traversing 2D Arrays

AP Computer Science A· difficulty 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

Explanation

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

Want 10 more like this — adaptive to your weak spots?

Related questions