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 Grid : ARRAY[1:2, 1:3] OF INTEGER
Grid[1,1] ← 5
OUTPUT Grid[1,1] // → 5
Two indexes: row, column
- Use
Grid[Row, Column]to reach one cell. - The first cell is
Grid[1,1].
DECLARE Grid : ARRAY[1:2, 1:2] OF INTEGER
Grid[1,2] ← 7
Grid[2,1] ← 9
OUTPUT Grid[1,2] // → 7
Nested FOR over a grid
- An outer loop walks the rows; an inner loop walks the columns.
DECLARE Grid : ARRAY[1:2, 1:3] OF INTEGER
DECLARE Row, Column : INTEGER
FOR Row ← 1 TO 2
FOR Column ← 1 TO 3
Grid[Row, Column] ← Row * Column
NEXT Column
NEXT Row
FOR Row ← 1 TO 2
FOR Column ← 1 TO 3
OUTPUT Grid[Row, Column]
NEXT Column
NEXT Row
Watch out
- The order is
Grid[Row, Column]— row first, then column.
Common mistakes
- A 2-D array is
ARRAY[1:RowCount, 1:ColumnCount]; 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.
Difficulty 3/5 · 200 coins + a small bonus on first completion today
Declare a 2×2 grid Grid. Store 1 in Grid[1,1] and 4 in Grid[2,2], then output their sum (it is 5).
Click Run to see the output here.
Difficulty 3/5 · 200 coins + a small bonus on first completion today
Fill a 2×3 grid Grid 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.
Difficulty 3/5 · 200 coins + a small bonus on first completion today
Use a loop to output a 3-by-3 square of stars: three lines, each with three *. OUTPUT takes several values separated by commas.
Click Run to see the output here.