Task 1 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 — creating and indexing

Lesson

A table of rows and columns

A two-dimensional array stores values in a grid of rows and columns. You reach a value with two indices: grid[r][c], where r is the row and c is the column. Both count from 0, so grid[0][0] is the top-left element.


Worked example

int[][] grid = {{1, 2, 3}, {4, 5, 6}};

System.out.println(grid[0][0]);   // 1  (top-left)
System.out.println(grid[1][2]);   // 6  (row 1, col 2)

The first bracket picks the row; the second picks the column within that row.


▶ Try it: run this, then change a value in the grid or the indices you print, and re-run.



In grid[r][c], the first index r selects the...


For int[][] grid = {{1, 2, 3}, {4, 5, 6}};, what is grid[1][2]?


For {{1, 2, 3}, {4, 5, 6}}, match each access to its value.


Fill the indices to read the value 6 (row 1, column 2) from grid.


True or false?


Type exactly what this program prints.

public class Main { public static void main(String[] a){
    int[][] g = {{1, 2}, {3, 4}};
    System.out.println(g[1][0]);
    System.out.println(g.length);
}}