LearnStanmorephysics

Grade 12 · Matric Mastery

2D arrays: rows & columns

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 20

What you will do

Hints
  1. Start each row's line as arrProv[iRow] + ':' — then the inner loop appends ' ' + the value.
  2. The element is arrRain[iRow, iCol] — row first, column second.
  3. 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;

About this material

This platform provides original CAPS-aligned practice material and study tools. Content is machine-verified and has not been reviewed by subject specialists. It is not affiliated with or endorsed by the Department of Basic Education. Learners should also use official past papers and consult their teachers where uncertain.