CDA - 2D Arrays Lesson

2D Arrays

Two-Dimensional Arrays

2DArrayGridA two-dimensional array is really an array full of arrays. In math, we call them matrices. Two-dimensional arrays have rows and columns. We created a grid of rows and columns in Module 5 using nested for loops and rectangles. However, you would not be able to access or manipulate the information inside the grid very easily. The information in the 2d array is stored in indexed locations which makes it easier to manipulate the information.  

The information in the 2D array is accessed by row and column. Index location (2, 3) is shown on the grid to the right. The row is listed first, then the column.    

Declare and Create Two-Dimensional Arrays

The general form for creating a two-dimensional array is as follows:

<Type> [][] nameOfArray = new <Type>[numRows][numCols];

  The <Type> refers to what is being stored in the two-dimensional array. The two sets of brackets indicate that we are creating a two-dimensional array instead of a one-dimensional array. Similar to arrays, we have to set the size of the array at the time of declaration. We have to specify the number of rows and columns when we create the two-dimensional array.  

Here is an example of a two-dimensional array:

 two-dimensional array:
int {}{} grid = new int ( 4)(4)

We can also create two-dimensional arrays using an initializer list. Each row does not have to store the same number of elements.  Below shows an example of a jagged array.  

int {}{} grid = { { 1,2,3,4,)} , { 1,2,3,) 

table

Accessing Elements in a Two-Dimensional Array

We access elements in a two-dimensional array similar to the way that we access elements in a one-dimensional array. We need to list the index of the row first and the column second. Consider the following assignments and how they will change the two-dimensional array square.

Table assignment with two-dimensional array square.

To get a value out of the two-dimensional array, you will access it in a similar way.

int x = grid[2][2];

The value of x will be 4.

Size of the Two-Dimensional Array

Not all two-dimensional arrays are squares. We will need to be able to get the number of rows and the number of columns. We get the number of rows the same way that we get the length of a one-dimensional array.

int rows = grid.length;

Each row in a two-dimensional array can have a different number of columns, so we will access the number of columns based on what row we are on. To get the number of columns in row 0, we will write the following:

int cols = grid[0].length;

To get the number of columns in different rows, we just need to change the row number.

[CC BY 4.0] UNLESS OTHERWISE NOTED | IMAGES: LICENSED AND USED ACCORDING TO TERMS OF SUBSCRIPTION