0984

Arrays

Programming · 4 question types

Exam Frequency Analysis

Past paper frequency (2018 to 2024)

This topic accounts for approximately 5% of your exam marks.

stable
Rare
Stable5%

1D array manipulation with FOR loops appears regularly in Paper 2. 4 to 6 marks.

To visit every element of a 2D array, you need a nested loop: one for the rows, one for the columns.

DECLARE Row : INTEGER
DECLARE Col : INTEGER

FOR Row ← 1 TO 3
   FOR Col ← 1 TO 3
      OUTPUT Grid[Row, Col]
   NEXT Col
NEXT Row

The outer loop steps through each row; for each row, the inner loop steps through every column. The output for the Grid example above is:

1
2
3
4
5
6
7
8
9

This prints the grid one row at a time, left to right.

Summing a 2D array

DECLARE Total : INTEGER
Total ← 0

FOR Row ← 1 TO 3
   FOR Col ← 1 TO 3
      Total ← Total + Grid[Row, Col]
   NEXT Col
NEXT Row

OUTPUT "Total: ", Total

For the example grid (1 to 9), the total is 45.

Counting matching cells

Count how many cells contain the number 0 in a noughts-and-crosses board:

DECLARE EmptyCount : INTEGER
EmptyCount ← 0

FOR Row ← 1 TO 3
   FOR Col ← 1 TO 3
      IF Board[Row, Col] = 0
        THEN
           EmptyCount ← EmptyCount + 1
      ENDIF
   NEXT Col
NEXT Row

OUTPUT "Empty squares: ", EmptyCount