Traversing 2D Arrays

AP Computer Science A· difficulty 4/5

To process a 2D array <code>int[][] grid</code> row by row, the standard nested loop is

  • A

    Single loop using grid[0].length only

  • B

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

  • C

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

    check_circle
  • D

    Single loop using grid.length only

Explanation

Outer loop iterates rows (grid.length), inner iterates columns in that row (grid[r].length, allowing jagged arrays). Choice (B) is column-major traversal, also valid for square arrays.

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

Related questions