Task 3 of 9 · 0 solved · 9 to go0%
You can read the problem, but answers are checked only for signed-in students. Sign in to answer →

5.4 2D arrays — dimensions and nested traversal

Lesson

How big is the grid?

grid.length is the number of rows. For a given row r, grid[r].length is the number of columns in that row. To visit every element, loop over the rows with an outer loop and over that row's columns with an inner loop — a nested loop.


Worked example

int[][] grid = {{1, 2, 3}, {4, 5, 6}};
for (int r = 0; r < grid.length; r++) {
    for (int c = 0; c < grid[r].length; c++) {
        System.out.print(grid[r][c] + " ");
    }
    System.out.println();
}

grid.length is 2 (two rows); each grid[r].length is 3 (three columns). The inner loop prints one row; println() then moves to the next line.


▶ Try it: run this to print the whole grid. Add a row or change a row's length and re-run — the nested loop still fits, because it uses grid.length and grid[r].length.



For {{1, 2, 3}, {4, 5, 6}}, what does grid.length give?


For the same grid, what does grid[0].length give?


Type exactly what this prints:

int[][] g = {{1, 2}, {3, 4}};
for (int r = 0; r < g.length; r++) {
    for (int c = 0; c < g[r].length; c++) {
        System.out.println(g[r][c]);
    }
}

Order the three parts of the inner loop header that walks a row's columns: for ( _ ; _ ; _ ).


True or false?