Traversing 2D Arrays

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

Explanation

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

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

Related questions