AP Computer Science A · Unit 4 lecture · Part 9 of 14 · 10 min

4.11-4.12 2D array creation, access and traversals2D arrays: rows and columns

Mr. Thompkins
Seats in a theater, pixels in a photo, a game board, a spreadsheet: so much data comes in rows and columns. Java stores it as an array of arrays.

A 2D array is an array whose elements are arrays. Its type has two pairs of brackets, like int[][]. new int[3][5] makes 3 rows of 5 columns, every element starting at its default. An initializer list is a list of rows, each row its own list in braces. To reach one element, give the row first and then the column: seats[2][4]. In this course, every 2D array is rectangular: all its rows have the same length.

1int[][] seats = new int[3][5];12String[][] board = { {"X", "O", "X"}, {"O", "X", "O"} };23seats[2][4] = 7;34System.out.println(seats.length + " " + seats[0].length);45System.out.println(board[1][2] + board[0][1] + " "6    + seats[2][4]);
  1. line 1 3 rows, 5 columns, every element 0
  2. line 2 An initializer list of rows: 2 rows, 3 columns
  3. line 3 Always [row][column]: the last row, last column
  4. line 4 length: rows. seats[0].length: columns
output › 3 5 OO 7
Making 2D arrays and reaching single elements.
274193856027col 0col 1col 2col 3row 0row 1row 2heatheat[1][2] is 8: row 1, then column 2heat[1] is the whole blue row
The heat array as a grid. Row first, then column.
?Wait, which comes first, the row or the column?
Always the row. heat[1][2] means row 1, column 2. A helpful phrase: rows run across like the rows of seats in a theater, and you pick your row before your seat.

Under the hood, the variable heat refers to an array of 3 elements, and each element is itself an int array of length 4: one whole row. That's why heat.length is the number of rows and heat[0].length, the length of the first row, is the number of columns.

heat[0][1][2]274193856027heat.length is 3each row is its own int[] of length 4for (int[] row : heat) visits these rows
An array of rows. heat[1] is a complete int[] you can store, pass or loop over.
?Wait, why does heat[1] work by itself?
heat[1] is the element at index 1 of the outer array, and that element is a 1D int array: {9, 3, 8, 5}. So int[] row = heat[1]; is legal, and row[2] is 8. It's a reference, so changing row[2] changes heat[1][2] too.

Traversals

Visiting every element takes nested loops. In row-major order, the outer loop goes over the rows and the inner loop over the columns of that row, so you read across each row, top to bottom. In column-major order, the loops trade places: the outer loop goes over columns and the inner over rows, so you read down each column, left to right. Either way, the element is still heat[r][c].

1int[][] heat = { {2, 7, 4, 1}, {9, 3, 8, 5}, {6, 0, 2, 7} };2for (int r = 0; r < heat.length; r++)13{4    for (int c = 0; c < heat[0].length; c++)15    {6        System.out.print(heat[r][c] + " ");7    }8    System.out.println();9}10for (int c = 0; c < heat[0].length; c++)211{12    for (int r = 0; r < heat.length; r++)213    {14        System.out.print(heat[r][c] + " ");315    }16}
  1. line 2-4 Row-major: rows outside, columns inside
  2. line 10-12 Column-major: columns outside, rows inside
  3. line 14 Still heat[r][c]. Only the loop order changed
output › 2 7 4 1 9 3 8 5 6 0 2 7 2 9 6 7 3 0 4 8 2 1 5 7
The same array, read row by row and then column by column.
row-majorcolumn-major123456789101112147102581136912outer loop: rowsacross, then downouter loop: columnsdown, then acrossnumbers show the visiting order
The order each traversal visits the 12 cells.

Nested enhanced for loops do a row-major traversal too. The outer variable is a whole row, so its type is int[]. The inner variable is one value of that row.

1int hot = 0;2for (int[] row : heat)13{4    for (int v : row)25    {6        if (v >= 7)7        {8            hot++;9        }10    }11}12System.out.println(hot);
  1. line 2 The outer variable is a whole row: an int[]
  2. line 4 The inner variable is one int in that row
output › 4
Counting values of 7 or more: 7, 9, 8 and 7.
Pause and think
In a row-major loop, what happens if the outer loop is written for (int r = 0; r < heat[0].length; r++)?
I thought about it. Show me
heat[0].length is 4, the number of columns, but there are only 3 rows. When r reaches 3, heat[3] doesn't exist and the code throws an ArrayIndexOutOfBoundsException. Rows come from heat.length; columns come from heat[0].length (or heat[r].length).
Trace a diagonal

Using the heat array, what does this print?

int total = 0;
for (int r = 0; r < heat.length; r++)
{
    total += heat[r][heat[r].length - 1 - r];
}
System.out.println(total);
  1. One loop, one element per row. heat[r].length is 4, so the column is 3 - r.
    Why?
    As r goes 0, 1, 2, the column goes 3, 2, 1: a diagonal from the top right moving down and to the left.
  2. r = 0: heat[0][3] is 1. r = 1: heat[1][2] is 8. r = 2: heat[2][1] is 0.
  3. 1 + 8 + 0 = 9.

Answer: 9

Stuck? Get a hint
  1. Work out the column index for each row first.
  2. For r = 1 the column is 4 - 1 - 1 = 2.
  3. Look up the three elements in the grid and add them.
Check yourself
What is printed?
int[][] g = { {1, 2, 3}, {4, 5, 6} };
int total = 0;
for (int c = 0; c < g[0].length; c++)
{
    total += g[1][c] - g[0][c];
}
System.out.println(total + " " + g.length);
  1. A9 2
  2. B9 3
  3. C3 2
  4. D21 2
Show the answer

A. The loop runs over the 3 columns and adds row 1 minus row 0 in each: 3 + 3 + 3 = 9. g.length counts rows, and there are 2. The second choice is the trap: 3 is the number of columns, g[0].length.

  • new int[rows][cols]; an initializer list is a list of rows. Access with g[row][col].
  • g.length is the number of rows; g[0].length is the number of columns.
  • A 2D array is an array of rows: g[r] is a whole 1D array.
  • Row-major: rows outside, columns inside. Column-major: the reverse. The element is always g[r][c].
  • for (int[] row : g) and then for (int v : row) visits every value in row-major order.