2D Arrays Grade 12

A two-dimensional array stores data in a grid of rows and columns — like a table or spreadsheet. Each element is accessed using two indices: [row, column].

T2Term 2 · 2D Arrays — Declaration & Processing

What is a 2D Array?

A two-dimensional (2D) array is a single variable that stores many values arranged in a grid of rows and columns. Where an ordinary (one-dimensional) array is like a single shopping list running down the page, a 2D array is like a whole spreadsheet — a block of cells where every value sits at the crossing point of a row and a column.

Analogy: think of a spreadsheet such as Excel. To find a cell you give a column letter and a row number — for example C5. A 2D array works exactly the same way, except we use two numbers: the first for the row and the second for the column. So myArray[2,3] means "the value in row 2, column 3", just like clicking one cell in a grid.

PURPOSE

We use 2D arrays to store tables of data that naturally have rows and columns — for example a class register of marks where each row is a learner and each column is a subject, a seating plan, a noughts-and-crosses board, or temperatures recorded for each day across several weeks. One neat variable holds the whole table instead of dozens of separate variables.

Why Do We Use 2D Arrays?

Declaration

Before you can use a 2D array you must declare it, telling Delphi how many rows and columns it has and what type of data each cell holds. You give two ranges in the square brackets: the first range is the rows and the second is the columns.

Syntax
var
  arrName : array [rowStart..rowEnd, colStart..colEnd] of DataType;
Delphi — 2x3 integer array
var
  myArray : array [1..2, 1..3] of Integer;

The example above creates a grid with 2 rows and 3 columns, giving 6 integer cells in total. Note: the ranges can start at any number, but in CAPS we almost always start at 1 so that "row 1" really is the first row.

Visualising a 2D Array

The table below shows how the index numbers map onto the grid. Read it like a spreadsheet: pick a row down the side and a column across the top, and the cell where they meet is the array element you are referring to.

Col 1Col 2Col 3
Row 1myArray[1,1]myArray[1,2]myArray[1,3]
Row 2myArray[2,1]myArray[2,2]myArray[2,3]

Populating a 2D Array

Populating means putting values into the cells. There are two common ways: assigning each cell one by one (fine for a few known values), or using nested loops to fill the whole grid quickly.

Fixed values

Here we set each cell directly by naming its row and column. This is clear but tedious — imagine doing it for a 30 × 6 register. Use it only when you have a handful of specific values to place.

Delphi
myArray[1,1] := 10;  myArray[1,2] := 20;  myArray[1,3] := 30;
myArray[2,1] := 40;  myArray[2,2] := 50;  myArray[2,3] := 60;

Nested FOR loops (most common)

This is the technique you will use most often. The outer loop moves through the rows; for each row the inner loop moves through every column. The result is that the inner loop runs completely for each turn of the outer loop, so the code visits every cell, one full row at a time — exactly like reading a spreadsheet left-to-right, then dropping down to the next line.

Delphi
var
  myArray : array [1..3, 1..4] of Integer;
  r, c    : Integer;
begin
  for r := 1 to 3 do
    for c := 1 to 4 do
      myArray[r, c] := r * c;   // e.g. row 2, col 3 = 6
end;

Displaying a 2D Array

To show the grid neatly we again use nested loops, but this time we build up one line of text per row. For each row we start with an empty string, add every column value to it (padding each so the columns line up), and only then add the finished line to the memo. Important Rule: the line is built inside the inner loop but written out in the outer loop — that is what keeps each row on its own line.

Delphi — display as table in memo
var
  sLine, sNum: string;
  r, c:  Integer;
begin
  memOut.Clear;
  for r := 1 to 3 do
  begin
    sLine := '';
    for c := 1 to 4 do
    begin
      sNum := IntToStr(myArray[r,c]);
      while Length(sNum) < 5 do       // pad with spaces until 5 characters wide
        sNum := ' ' + sNum;
      sLine := sLine + sNum;
    end;
    memOut.Lines.Add(sLine);
  end;
end;
Why not PadLeft?

Newer Delphi versions have a built-in .PadLeft() string helper that does this in one call, but it is not part of CAPS. The WHILE loop above achieves the same result — adding a space in front of the number until it is 5 characters wide — using only Length, string concatenation and a loop, all of which are already CAPS-examinable.

Building the Whole Grid as One String

Another way to display the grid is to build one long string that holds every row, and give it to a RichEdit in a single step. The outer loop handles the rows and the inner loop handles the columns. After each value we add a tab (#9) so the columns line up, and after each finished row we add a line break (#13#10). Here arrSales holds tuckshop sales (row = item, column = day) and iRows and iCols say how many rows and columns are in use.

Delphi — grid string built row by row, shown in a RichEdit
var
  r, c          : Integer;
  sLine, sGrid  : string;
begin
  sGrid := '';                                   // the whole grid starts empty
  for r := 1 to iRows do
  begin
    sLine := '';                                 // each row starts a fresh line
    for c := 1 to iCols do
      sLine := sLine + IntToStr(arrSales[r, c]) + #9;   // value, then a tab
    sGrid := sGrid + sLine + #13#10;              // finished row, then a new line
  end;
  redGrid.Text := sGrid;                          // show everything at once
end;
Trap — where each string is reset

sGrid is cleared before both loops (once), sLine is cleared at the start of every row (inside the outer loop), and redGrid.Text is assigned after both loops. Clear sLine in the wrong place and the rows run into each other; assign the Text inside the loop and you only see the last row.

TStringGrid as an Alternative Display

The TStringGrid component (listed in the CAPS component list for Grades 11 and 12) shows a real table with cells and gridlines. You fill it cell by cell with the Cells property — but note that Cells takes the column first, then the row, the opposite order from your array. A new string grid has one fixed header row and one fixed header column at index 0, so the data for arrSales[r, c] fits neatly into Cells[c, r].

Delphi — show the array in a TStringGrid
strSales.RowCount := iRows + 1;     // +1 for the fixed header row
strSales.ColCount := iCols + 1;     // +1 for the fixed header column
for r := 1 to iRows do
  for c := 1 to iCols do
    strSales.Cells[c, r] := IntToStr(arrSales[r, c]);   // [column, row]!

Calculations on 2D Arrays

A big reason for using a grid is to add things up. The trick is knowing which index to fix and which to vary. If you think of the class register again: a row total is one learner's marks added across all subjects, while a column total is one subject's marks added across all learners.

Row total

To total a single row we fix the row number (here row 1) and let the column index c change. The loop walks across that one row, adding each cell to a running total. This answers "what is everything in this row added together?" — for example one learner's total mark.

Delphi — total of row 1
iTotal := 0;
for c := 1 to 4 do
  iTotal := iTotal + myArray[1, c];

Column total

Now we do the opposite: we fix the column number (here column 2) and let the row index r change. The loop runs straight down that one column, adding each cell. This answers "what is everything in this column added together?" — for example the total of all learners' marks for one subject.

Delphi — total of column 2
iTotal := 0;
for r := 1 to 3 do
  iTotal := iTotal + myArray[r, 2];

Grand total of all elements

To add up every cell in the whole grid we need nested loops again — the outer loop for rows, the inner loop for columns — so the running total picks up each cell exactly once. This is how you would work out the grand total of all marks for the entire class across all subjects.

Delphi
iTotal := 0;
for r := 1 to 3 do
  for c := 1 to 4 do
    iTotal := iTotal + myArray[r, c];

Worked Example — Class Register Report

A full exam question ties the pieces together: a 2D array of marks, a parallel 1D array of names, nested loops, and both a row and a column calculation. Here the grid arrMark holds marks for each learner (rows) across 4 subjects (columns), and arrName holds the matching learner names.

Delphi — global declarations
const
  LEARNERS = 5;
  SUBJECTS = 4;
var
  arrMark : array[1..LEARNERS, 1..SUBJECTS] of Integer;   // the grid: row = learner, col = subject
  arrName : array[1..LEARNERS] of string;              // parallel to the rows

arrName[r] is the name of the learner whose marks are in arrMark[r, 1..SUBJECTS] — the name array runs parallel to the rows of the grid.

Part (a) — Each learner's average (a row calculation)

Fix the row (one learner) and loop across the columns to total their subjects, then divide.

Delphi — print name + average per learner
var
  r, c, iRowTotal : Integer;
  rAvg            : Real;
begin
  for r := 1 to LEARNERS do
  begin
    iRowTotal := 0;
    for c := 1 to SUBJECTS do
      iRowTotal := iRowTotal + arrMark[r, c];
    rAvg := iRowTotal / SUBJECTS;
    memOut.Lines.Add(arrName[r] + ': ' +
                     FloatToStrF(rAvg, ffFixed, 4, 1) + '%');
  end;
end;

Part (b) — The best subject (a column calculation + finding a max)

Now fix each column (one subject) and loop down the rows to average that subject across all learners, keeping track of the highest.

Delphi — subject with the highest class average
var
  r, c, iColTotal, iBestCol : Integer;
  rColAvg, rBestAvg         : Real;
begin
  iBestCol := 1;
  rBestAvg := 0;
  for c := 1 to SUBJECTS do
  begin
    iColTotal := 0;
    for r := 1 to LEARNERS do
      iColTotal := iColTotal + arrMark[r, c];
    rColAvg := iColTotal / LEARNERS;
    if rColAvg > rBestAvg then
    begin
      rBestAvg := rColAvg;
      iBestCol := c;               // remember WHICH subject
    end;
  end;
  ShowMessage('Best subject: column ' + IntToStr(iBestCol) +
              ' (average ' + FloatToStrF(rBestAvg, ffFixed, 4, 1) + '%)');
end;
The pattern to remember

Row calculation → fix the row, loop the columns (one learner across all subjects). Column calculation → fix the column, loop the rows (one subject down all learners). To find a "best/worst", store the index as you go — that index links straight back to the parallel arrName.

Changing, Moving and Removing Elements

A 2D array is usually declared bigger than the data you currently have. Two counters, iRows and iCols, record how much of it is in use, and every loop runs to those counters — not to the declared size. The examples below all use this array of tuckshop sales:

Delphi — declarations for the next four examples
const
  MAXROWS = 10;
  MAXCOLS = 5;
var
  arrSales     : array[1..MAXROWS, 1..MAXCOLS] of Integer;
  iRows, iCols : Integer;        // how many rows / columns are actually filled
  r, c, iTemp  : Integer;

Replace a single element

Name the row and column and assign the new value. Whatever was in that cell is overwritten.

Delphi
arrSales[iRow, iCol] := iNewValue;

Swap two specified elements

You cannot simply copy one cell onto the other, because the first value would be lost. Park it in a temporary variable first, exactly as when swapping two ordinary variables.

Delphi — swap arrSales[r1,c1] with arrSales[r2,c2]
iTemp := arrSales[r1, c1];                // 1. save the first value
arrSales[r1, c1] := arrSales[r2, c2];     // 2. second value moves to the first cell
arrSales[r2, c2] := iTemp;                // 3. saved value goes into the second cell

Delete a row

A fixed-size array cannot actually get shorter — it keeps its capacity. To "delete" a row you copy every later row one position up, over the row being removed, and then reduce the occupied row count by one so the leftover last row is ignored. To delete row 3 of 6: row 4 is copied into row 3, row 5 into row 4, row 6 into row 5, and iRows becomes 5.

Delphi — remove row iDelRow
for r := iDelRow to iRows - 1 do       // stop one row early: r + 1 must still be in use
  for c := 1 to iCols do
    arrSales[r, c] := arrSales[r + 1, c];   // copy the next row up
Dec(iRows);                             // one row fewer in use
Trap — the loop must stop at iRows - 1

If the outer loop runs all the way to iRows, the last pass reads arrSales[iRows + 1, c], a row that is not in use — and if the array is full, one that does not exist at all, which crashes with a range error. Also work from the deleted row downwards, never upwards, or you copy over rows you have not moved yet.

Transpose a matrix into a second array

To transpose a grid is to turn its rows into columns. The cell at row r, column c in the original goes to row c, column r in the copy. Because the dimensions swap, a rectangular matrix needs a second array declared with the dimensions the other way round.

Delphi — copy arrSales into arrFlip, rows and columns exchanged
var
  arrFlip : array[1..MAXCOLS, 1..MAXROWS] of Integer;   // dimensions swapped
begin
  for r := 1 to iRows do
    for c := 1 to iCols do
      arrFlip[c, r] := arrSales[r, c];
  // arrFlip now uses iCols rows and iRows columns
end;
Original (2 rows × 3 columns)Transposed (3 rows × 2 columns)
10   20   30
40   50   60
10   40
20   50
30   60

Worked Example — Building Each Row from the Row Above

Some patterns are not typed in; they are calculated. Here we have a grid of 6 rows and 11 columns. Rows 1 and 2 are supplied. For every later row, each interior cell is the sum of the two diagonal neighbours above it — the cell in the previous row one column to the left, plus the cell in the previous row one column to the right. The first and last columns are never touched and stay 0.

1234567891011
Row 100000200000
Row 200002020000
Row 300020402000
Row 400206060200
Row 5020801208020
Row 6001002002001000

Check one cell by hand: row 3, column 6 = row 2 column 5 (which is 2) + row 2 column 7 (which is 2) = 4.

Delphi — fill rows 3 to 6 from the row above
const
  ROWS = 6;
  COLS = 11;
var
  arrPat : array[1..ROWS, 1..COLS] of Integer;
  r, c   : Integer;
begin
  // clear every cell so the untouched edge columns really are 0
  for r := 1 to ROWS do
    for c := 1 to COLS do
      arrPat[r, c] := 0;

  // the two supplied rows
  arrPat[1, 6] := 2;
  arrPat[2, 5] := 2;
  arrPat[2, 7] := 2;

  // rows 3 to 6: top to bottom, interior columns only
  for r := 3 to ROWS do
    for c := 2 to COLS - 1 do
      arrPat[r, c] := arrPat[r - 1, c - 1] + arrPat[r - 1, c + 1];
end;
Why these loop limits?

Rows from 3 to ROWS, top to bottom: each row depends on the one above it, so the row above must already be finished when you reach it. Columns from 2 to COLS - 1: a cell in column 1 would need arrPat[r - 1, 0] and one in column 11 would need arrPat[r - 1, 12]; neither column exists, so those edge cells are skipped and keep their 0.

A two-dimensional array element is accessed using…

e.g. arr[r, c] — the first picks the row, the second the column.

To total the values in one row, you keep the row fixed and loop the…

Hold the row number constant and move across every column in that row.

To process (fill/total) an entire 2D array you normally use…

An outer loop for the rows and an inner loop for the columns visits every cell.