Two-Dimensional Arrays

Two-dimensional arrays are used when programs model data laid out as a grid or matrix.  While one-dimensional arrays are indexed by a single value, two-dimensional arrays have two indexes separated by a comma in the square brackets following the variable name.   We can visualize a two-dimensional array called grid as below, where the names of the array elements are shown, not their values:  

 

grid[1,1]

grid[1,2]

grid[1,3]

grid[1,4]

grid[2,1]

grid[2,2]

grid[2,3]

grid[2,4]

grid[3,1]

grid[3,2]

grid[3,3]

grid[3,4]

 

The numbers in the square brackets are the row and column indexes.  They distinguish between the different variables falling under the name grid.  

 

Below is a slightly different visualization, this time showing sample values in the variable memory locations and the indexes above and to the left of them.

 

grid

1

2

3

4

1

3

8

6

15

2

2

9

12

14

3

6

11

18

13

 

With the example values above, grid[3,2] has the value 11, and grid[2,4] has the value 14.

 

Processing Two-Dimensional Arrays

 

One-dimensional arrays are often processed using counting loops.  To process all elements of a two-dimensional array, nested loops, one inside the other, must be used.  Usually, the outer loop counts through the rows (in the example above, it would count from 1 to 3), while the inner loop counts through the columns (from 1 to 4 in the example).   The example below determines the sum of all elements in the grid array.