Grade 12 · Two-dimensional arrays · Lesson and coding task · about 14 minutes
Open this task in the Delphi workspace →
A two-dimensional array is a grid — rows and columns under one name:
arrRain : array[1..3, 1..4] of Integer;
// 3 provinces (rows), 4 weeks (columns)
arrRain[2, 3] // row 2, column 3
Wherever a 1D array wanted one FOR loop, a 2D array wants two — the outer loop walks the rows, the inner loop walks the columns of that row:
for iRow := 1 to 3 do
begin
sLine := arrProv[iRow] + ':';
for iCol := 1 to 4 do
sLine := sLine + ' ' + IntToStr(arrRain[iRow, iCol]);
memOutput.Lines.Add(sLine);
end;
Say the indices out loud as "row comma column" every single time — swapping them is the classic 2D bug (and with a non-square grid it crashes).
Your task
Rainfall (mm) was recorded for 3 provinces over 4 weeks (constant array in the starter). Display the grid, one province per line:
Gauteng: 12 0 5 20What you will do
- Nested FOR loops: rows outside, columns inside
- Each line starts with the province name and a colon, then the 4 values each preceded by a space
- Line 1 is exactly: Gauteng: 12 0 5 20
Hints
- Start each row's line as arrProv[iRow] + ':' — then the inner loop appends ' ' + the value.
- The element is arrRain[iRow, iCol] — row first, column second.
- Add the line to the memo after the inner loop finishes (still inside the outer loop).
Model solution
const
arrProv : array[1..3] of String = ('Gauteng', 'KwaZulu-Natal', 'Western Cape');
arrRain : array[1..3, 1..4] of Integer = ((12, 0, 5, 20), (3, 8, 0, 11), (25, 14, 7, 0));
procedure TfrmRain.btnGridClick(Sender: TObject);
var
iRow, iCol : Integer;
sLine : String;
begin
for iRow := 1 to 3 do
begin
sLine := arrProv[iRow] + ':';
for iCol := 1 to 4 do
sLine := sLine + ' ' + IntToStr(arrRain[iRow, iCol]);
memOutput.Lines.Add(sLine);
end;
end;