2D Arrays
- Create a 2D array and access an element with `[row][col]`
- Find the number of rows and columns from the array’s length fields
- Trace element access in a rectangular grid
A grid of rows and columns
A 2D array is an array of arrays — a grid. int[][] grid = {{1, 2, 3}, {4, 5, 6}}; has 2 rows and 3 columns. You access an element with two indices, grid[row][col], both zero-based. grid[0] is the first row {1, 2, 3}, and grid[1][2] is row 1, column 2.
Rows first, then columns
The first index selects the row, the second selects the column within that row. So grid[1][2] means "go to row 1, then column 2." Reading these in the right order is essential: grid[2][1] would be a different (and possibly invalid) element.
Counting rows and columns
For a rectangular 2D array, m.length gives the number of rows, and m[0].length gives the number of columns (the length of the first row). new int[3][4] therefore has 3 rows and 4 columns, all initialized to the default 0. To visit every cell, nest a column loop inside a row loop.
Trace this code: int[][] grid = {{1, 2, 3}, {4, 5, 6}}; then System.out.println(grid[1][2]);
- 1.Row 0 is {1, 2, 3}; row 1 is {4, 5, 6}.
- 2.
grid[1]selects row 1: {4, 5, 6}. - 3.
grid[1][2]then selects column 2 of that row. - 4.Column 2 of {4, 5, 6} is 6 (indices 0, 1, 2 → 4, 5, 6).
6 — row 1, column 2 of the grid.What does this print? `int[][] grid = {{1, 2, 3}, {4, 5, 6}};` then `System.out.println(grid[1][2]);`
Always read [row][col]: the first bracket is the row, the second is the column. Swapping them is the most common 2D-array mistake.
What does this print? `int[][] m = new int[3][4];` then `System.out.println(m.length + " " + m[0].length);`
To traverse a full grid, use for (int r = 0; r < m.length; r++) outside and for (int c = 0; c < m[0].length; c++) inside. The outer loop walks rows, the inner walks columns.
Answer the 2 checkpoints as you read.
Sign in to save your progress