2-D arrays
This page needs a recent browser (with SharedArrayBuffer support). Please update Chrome, Edge, Firefox or Safari to the latest version.
Rows and columns
- A two-dimensional array is a grid. The declaration gives both bounds.
- Two indexes, separated by a comma, pick a cell: row, then column.
DECLARE Grid : ARRAY[1:2, 1:2] OF INTEGER
Grid[1, 1] ← 4
Grid[1, 2] ← 7
OUTPUT Grid[1, 2]
One loop inside another
- The outer loop walks the rows. The inner loop walks the columns of that row.
NEXTnames the counter of the loop it closes.
DECLARE Grid : ARRAY[1:2, 1:2] OF INTEGER
Grid[1, 1] ← 1
Grid[1, 2] ← 2
Grid[2, 1] ← 3
Grid[2, 2] ← 4
DECLARE Total : INTEGER
Total ← 0
FOR Row ← 1 TO 2
FOR Column ← 1 TO 2
Total ← Total + Grid[Row, Column]
NEXT Column
NEXT Row
OUTPUT Total
Common mistakes
- Write
Grid[1, 2], with a comma. Both indexes start at the declared lower bound. - The inner
NEXTcomes before the outer one.
Now you try
- Read one cell of a 2-D array, then total the grid.
Declare Grid as ARRAY[1:2, 1:2] OF INTEGER. Store 7 in row 1, column 2, and output that cell.
Click Run to see the output here.
The grid is filled for you. Total all four cells and output the total (10).
Click Run to see the output here.