2-D arrays
This page needs a recent browser (with SharedArrayBuffer support). Please update Chrome, Edge, Firefox or Safari to the latest version.
A 2-D array is a grid
- A 2-D array has rows and columns, like a table.
ARRAY[1:2, 1:3]means 2 rows and 3 columns.
DECLARE G : ARRAY[1:2, 1:3] OF INTEGER
G[1,1] ← 5
OUTPUT G[1,1] // → 5
Two indexes: row, column
- Use
G[row, column]to reach one cell. - The first cell is
G[1,1].
DECLARE G : ARRAY[1:2, 1:2] OF INTEGER
G[1,2] ← 7
G[2,1] ← 9
OUTPUT G[1,2] // → 7
Nested FOR over a grid
- An outer loop walks the rows; an inner loop walks the columns.
FOR r ← 1 TO 2
FOR c ← 1 TO 3
OUTPUT G[r, c]
NEXT c
NEXT r
Watch out
- The order is
G[row, column]— row first, then column. - The inner
NEXT cmust close before the outerNEXT r.
Common mistakes
- A 2-D array is
ARRAY[1:r, 1:c]; use two indexes. - The outer loop walks the rows, the inner the columns.
Now you try
- Use two indexes, or nested
FORloops. - Press Check answer to test it.
Declare a 2×2 grid G. Store 1 in G[1,1] and 4 in G[2,2], then output their sum (it is 5).
Click Run to see the output here.
Fill a 2×3 grid G so each cell holds row × column, then add up every cell with nested loops and output the total (it is 18).
Click Run to see the output here.
Use nested loops to output a 3-by-3 square of stars: three lines, each with three *.
Click Run to see the output here.