2-D arrays
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.
Write one cell, then read it back.
![A 2-D array as a grid of rows and columns; G[1,2] is the cell in row 1, column 2](/static/code/as-pseudocode/array-2d-seats.png)
DECLARE Seats : ARRAY[1:3, 1:4] OF STRING
Seats[2, 3] ← "Mei"
Seats[3, 1] ← "Ola"
OUTPUT "Row 2, seat 3: ", Seats[2, 3]
OUTPUT "Row 3, seat 1: ", Seats[3, 1]
ARRAY[1:3, 1:4]is 3 rows by 4 columns: 12 cells. The row index always comes first.
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 Sales : ARRAY[1:2, 1:3] OF INTEGER
DECLARE Shop, Day, ShopTotal : INTEGER
Sales[1, 1] ← 5
Sales[1, 2] ← 8
Sales[1, 3] ← 2
Sales[2, 1] ← 6
Sales[2, 2] ← 1
Sales[2, 3] ← 9
FOR Shop ← 1 TO 2
ShopTotal ← 0
FOR Day ← 1 TO 3
ShopTotal ← ShopTotal + Sales[Shop, Day]
NEXT Day
OUTPUT "Shop ", Shop, ": ", ShopTotal
NEXT Shop
- Each row is one shop, each column one day. The inner loop adds up one row.
ShopTotal ← 0sits inside the outer loop, so each shop starts again from 0. For one total of the whole grid, set it to 0 once, before both loops.
The inner loop runs all the way for each row.
Pick a cell of Sales: row (shop) first, then column (day)
Sales[2, 3] is row 2, column 3. Both indexes start at 1.
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 every cell of a grid.
Independent transfer
The final task has no supplied algorithm. Plan its inputs, processing and outputs, then solve it before opening support. Check more than the sample case.
ความยาก 2/5 · 140 เหรียญ + บอนัสน้อยๆ เมื่อทำสำเร็จครั้งแรกในวันนี้
Declare Grid as ARRAY[1:2, 1:2] OF INTEGER. Store 7 in row 1, column 2, and output that cell.
คลิก Run เพื่อดูผลลัพธ์ที่นี่
ความยาก 2/5 · 140 เหรียญ + บอนัสน้อยๆ เมื่อทำสำเร็จครั้งแรกในวันนี้
The grid is filled for you. Total all four cells and output the total (10).
คลิก Run เพื่อดูผลลัพธ์ที่นี่
ความยาก 3/5 · 200 เหรียญ + บอนัสน้อยๆ เมื่อทำสำเร็จครั้งแรกในวันนี้
Read a 2 by 2 array row by row. Output the number of positive values in column 1, then column 2.
คลิก Run เพื่อดูผลลัพธ์ที่นี่