 # Yorkville High School Computer Science

ASSIGNMENTS: Hidden Figure - May 24, 2019

## AP Computer Science :: Lessons :: 2D Arrays Chapter 7:
Pages 264 - 268

Fundamentals of Java
Chapter 9
Pages 318 - 322

### 2D Arrays

A two-dimensional array, also known as a matrix, is simply an array that holds arrays. It is used quite often for tables of values (such as the cells in Excel), mazes, and games based on grids. Other multi-dimensional arrays can be used, but the increase in memory can be dramatic so normally nothing past 3D arrays is used.

```1 6 1 8
0 3 3 9
8 8 7 4
```

The above numbers make up a 3 x 4 rectangular matrix. A rectangular matrix is one in which each row has the same number of elements. We will only deal with rectangular matrices in AP Computer Science, but it is possible to create a jagged array that does not have the same number of elements in each row. There are a number of ways you can create the above matrix in Java. The first is by declaring the array and using an initializer list to set the values.

```int[][] matrix = {
{1, 6, 1, 8},
{0, 3, 3, 9},
{8, 8, 7, 4}
};```

The two pairs of square brackets indicate that this is a 2D array. Each set of curly brackets indicates a new row in the matrix. The initialization above would create the rectangular matrix we saw earlier. The example below will create the same matrix, but the array is not populated on the same line where it is declaorangeBold.

```int[][] matrix = new int;

matrix = 1;
matrix = 6;
matrix = 1;
matrix = 8;
matrix = 0;
matrix = 3;
matrix = 3;
matrix = 0;
matrix = 8;
matrix = 8;
matrix = 7;
matrix = 4;```

A 2D array element is accessed by specifying the row followed by the column. It is important that you remember the column is specified after the row.