Skip to content
Book 4: Practical Programming

Book 4 · Chapter P4.2

Arrays, 2D arrays and records

§10.1§10.2AS skills Paper 4 builds onBanker · ≈ 21.8 m · ↘B4·2

This chapter is in the ebook.

Read it in full on cswithzak.com. Every question has its mark scheme and every program is ready to run. The free practice for each section is below, with the short code the book prints beside it.

Open in the ebook

For the whole chapter

§10.1 Data types and records

Short code B4·2·1

From pseudocode arrays to real ones

Short code B4·2·10

# Rain : ARRAY[0:4] OF INTEGER (millimetres on each of 5 days)
Rain = [4, 0, 7, 2, 5]
Total = 0
for Day in range(0, 5):
    Total = Total + Rain[Day]
print("Total rain:", Total)
print("Day 1 had", Rain[0])
The faithful translation: the loop visits index 0 to 4, all five elements, so the total is 18.

Output

Total rain: 18
Day 1 had 4
Run and checked before printing

Declaring a 1D array

Short code B4·2·11

# Global arrays, declared before any subroutine
# Names : ARRAY[0:9] OF STRING
Names = [""] * 10
# Scores : ARRAY[0:9] OF INTEGER
Scores = [0] * 10

Names[0] = "Ayesha"
Scores[0] = 72
Names[9] = "Zain"
print(len(Names), "elements")
print("First:", Names[0], Scores[0])
print("Last:", Names[9], Scores[9])
Two global arrays of 10 elements. Every element exists from the start; the strings are filled with "" so none is left empty.

Output

10 elements
First: Ayesha 72
Last: Zain 0
Run and checked before printing

Index 0 or index 1?

Short code B4·2·12

PROCEDURE LowStock()
   DECLARE Index : INTEGER
   DECLARE Count : INTEGER
   Count ← 0
   FOR Index ← 1 TO 8
      IF Stock[Index] < 10 THEN
         OUTPUT Stock[Index]
         Count ← Count + 1
      ENDIF
   NEXT Index
   OUTPUT Count
ENDPROCEDURE

CALL LowStock()
The pseudocode the Mark Ladder translates, run on the CS with ZAK interpreter with Stock = 12, 4, 30, 9, 15, 10, 2, 22.
Run and checked before printing
Rainfall = [12, 30, 45, 8, 60, 22, 0, 15, 41, 33, 9, 50]

def CountOver(Limit):
    Count = 0
    for Index in range(0, 12):
        if Rainfall[Index] > Limit:
            Count = Count + 1
    return Count

print(CountOver(30))
print(CountOver(60))
Model answer (check) for Q10

Output

5
0
Run and checked before printing

Totals, largest, smallest and counts

Short code B4·2·13

# Temps : ARRAY[0:6] OF INTEGER (top temperature each day)
Temps = [21, 25, 19, 30, 26, 22, 25]

Total = 0
for Day in range(7):
    Total = Total + Temps[Day]
Mean = Total // 7

MaxIndex = 0
MinIndex = 0
for Day in range(1, 7):
    if Temps[Day] > Temps[MaxIndex]:
        MaxIndex = Day
    if Temps[Day] < Temps[MinIndex]:
        MinIndex = Day

Count = 0
for Day in range(7):
    if Temps[Day] > Mean:
        Count = Count + 1

print("Total", Total, "Mean", Mean)
print("Hottest: day", MaxIndex + 1, "at", Temps[MaxIndex])
print("Coolest: day", MinIndex + 1, "at", Temps[MinIndex])
print("Days above the mean:", Count)
Four standard jobs on one array: a total, the index of the largest and of the smallest value, and a count. The day number is the index + 1.

Output

Total 168 Mean 24
Hottest: day 4 at 30
Coolest: day 3 at 19
Days above the mean: 4
Run and checked before printing

Short code B4·2·14

# Codes : ARRAY[0:5] OF STRING
Codes = ["K2", "M7", "A1", "C7", "B4", "D9"]

def FindCode(Target):
    Index = 0
    Found = False
    while Index < 6 and not Found:
        if Codes[Index] == Target:
            Found = True
        else:
            Index = Index + 1
    if Found:
        return Index
    return -1

print("C7 is at index", FindCode("C7"))
print("Z1 is at index", FindCode("Z1"))
A linear search that stops at the first match. It returns the index, or −1 when every element has been checked.

Output

C7 is at index 3
Z1 is at index -1
Run and checked before printing

2D arrays in code

Short code B4·2·15

Wrong = [[0] * 3] * 2
Wrong[0][1] = 9
print(Wrong)
Right = [[0] * 3 for Row in range(2)]
Right[0][1] = 9
print(Right)
[[0] * 3] * 2 copies one row twice, so changing one element changes 'both rows'. The comprehension makes a new row each time.

Output

[[0, 9, 0], [0, 9, 0]]
[[0, 9, 0], [0, 0, 0]]
Run and checked before printing

Traversing a 2D array by row and by column

Short code B4·2·16

# Marks : ARRAY[0:3, 0:2] OF INTEGER (4 students, 3 tests)
Marks = [[12, 15, 9],
         [18, 11, 14],
         [7, 10, 13],
         [16, 18, 8]]

# By row: one student at a time
for Student in range(4):
    Total = 0
    for Test in range(3):
        print(Marks[Student][Test], end=" ")
        Total = Total + Marks[Student][Test]
    print("| total", Total)

# By column: one test at a time
for Test in range(3):
    Total = 0
    for Student in range(4):
        Total = Total + Marks[Student][Test]
    print("Test", Test + 1, "total", Total)
The same 2D array visited two ways. By row: the student loop is outside. By column: the test loop is outside, and Total restarts for each test.

Output

12 15 9 | total 36
18 11 14 | total 43
7 10 13 | total 30
16 18 8 | total 42
Test 1 total 53
Test 2 total 54
Test 3 total 44
Run and checked before printing

Choosing data types

Short code B4·2·17

import datetime

Title = "Coral Reefs"                     # STRING
Copies = 3                                # INTEGER
Rating = 4.5                              # REAL
Shelf = "C"                               # CHAR
OnLoan = True                             # BOOLEAN
DueDate = datetime.date(2027, 3, 14)      # DATE

DueDate = DueDate + datetime.timedelta(days=14)
print(Title, Copies, Rating, Shelf)
if OnLoan:
    print("On loan, due", DueDate)
One variable of each type. Only Python needs comments to show the types; the date arithmetic adds 14 days.

Output

Coral Reefs 3 4.5 C
On loan, due 2027-03-28
Run and checked before printing

Records in code

Short code B4·2·18

class Pupil:
    # A record type: fields only, no other methods
    def __init__(self):
        self.Name = ""      # STRING
        self.Form = ""      # CHAR
        self.Mark = 0       # INTEGER

Top = Pupil()
Top.Name = "Hassan"
Top.Form = "B"
Top.Mark = 88
print(Top.Name, "of form", Top.Form, "scored", Top.Mark)
A record type with three fields of different types, and one variable of that type. Each field is reached as Variable.Field.

Output

Hassan of form B scored 88
Run and checked before printing
from dataclasses import dataclass

@dataclass
class Pupil:
    Name: str = ""
    Form: str = ""
    Mark: int = 0

Top = Pupil("Hassan", "B", 88)
print(Top.Name, Top.Mark)
The same record as a Python dataclass: the field list with types is the declaration, and the constructor is written for you.

Output

Hassan 88
Run and checked before printing
Structure Pupil
    Public Name As String
    Public Mark As Integer
End Structure

Module Program
    Sub Main()
        Dim A As Pupil
        A.Name = "Hassan"
        A.Mark = 88
        Dim B As Pupil = A
        B.Mark = 50
        Console.WriteLine(A.Mark & " " & B.Mark)
    End Sub
End Module
VB.NET: B = A copies a Structure, so changing B leaves A alone.

Output

88 50
Run and checked before printing
class Pupil:
    def __init__(self):
        self.Name = ""
        self.Mark = 0

A = Pupil()
A.Name = "Hassan"
A.Mark = 88
B = A
B.Mark = 50
print(A.Mark, B.Mark)
Python (and Java): B = A copies the reference, so A and B are one record.

Output

50 50
Run and checked before printing

Arrays of records

Short code B4·2·19

class Pupil:
    # A record type: fields only, no other methods
    def __init__(self):
        self.Name = ""      # STRING
        self.Form = ""      # CHAR
        self.Mark = 0       # INTEGER

# Pupils : ARRAY[0:4] OF Pupil
Pupils = [None] * 5

def Store(Index, PName, PForm, PMark):
    NewPupil = Pupil()
    NewPupil.Name = PName
    NewPupil.Form = PForm
    NewPupil.Mark = PMark
    Pupils[Index] = NewPupil

Store(0, "Hassan", "B", 88)
Store(1, "Mina", "A", 45)
Store(2, "Omar", "B", 67)
Store(3, "Sara", "C", 39)
Store(4, "Tariq", "A", 71)

Total = 0
for Index in range(5):
    Total = Total + Pupils[Index].Mark
    if Pupils[Index].Mark >= 50:
        print(Pupils[Index].Name, Pupils[Index].Mark)
print("Mean mark", Total // 5)
An array of five records. One loop reads the Mark field of each element to list the passes and work out the mean.

Output

Hassan 88
Omar 67
Tariq 71
Mean mark 62
Run and checked before printing

Short code B4·2·20

class Pupil:
    # A record type: fields only, no other methods
    def __init__(self):
        self.Name = ""      # STRING
        self.Form = ""      # CHAR
        self.Mark = 0       # INTEGER

# Pupils : ARRAY[0:4] OF Pupil
Pupils = [None] * 5

def Store(Index, PName, PForm, PMark):
    NewPupil = Pupil()
    NewPupil.Name = PName
    NewPupil.Form = PForm
    NewPupil.Mark = PMark
    Pupils[Index] = NewPupil

Store(0, "Hassan", "B", 88)
Store(1, "Mina", "A", 45)
Store(2, "Omar", "B", 67)
Store(3, "Sara", "C", 39)
Store(4, "Tariq", "A", 71)

def FindPupil(SearchName):
    Index = 0
    while Index < 5:
        if Pupils[Index].Name == SearchName:
            return Index
        Index = Index + 1
    return -1

for Wanted in ["Sara", "Zoe"]:
    Position = FindPupil(Wanted)
    if Position == -1:
        print(Wanted + ": not found")
    else:
        print(Wanted + ": form", Pupils[Position].Form, "mark", Pupils[Position].Mark)
Searching an array of records: compare one field (Name), return the index, then use that index to read the other fields.

Output

Sara: form C mark 39
Zoe: not found
Run and checked before printing

Sorting records with a bubble sort

Short code B4·2·21

class Pupil:
    # A record type: fields only, no other methods
    def __init__(self):
        self.Name = ""      # STRING
        self.Form = ""      # CHAR
        self.Mark = 0       # INTEGER

# Pupils : ARRAY[0:4] OF Pupil
Pupils = [None] * 5

def Store(Index, PName, PForm, PMark):
    NewPupil = Pupil()
    NewPupil.Name = PName
    NewPupil.Form = PForm
    NewPupil.Mark = PMark
    Pupils[Index] = NewPupil

Store(0, "Hassan", "B", 88)
Store(1, "Mina", "A", 45)
Store(2, "Omar", "B", 67)
Store(3, "Sara", "C", 39)
Store(4, "Tariq", "A", 71)

def SortByMark():
    Top = 4
    Swapped = True
    while Swapped and Top > 0:
        Swapped = False
        for Index in range(Top):
            if Pupils[Index].Mark < Pupils[Index + 1].Mark:
                Temp = Pupils[Index]
                Pupils[Index] = Pupils[Index + 1]
                Pupils[Index + 1] = Temp
                Swapped = True
        Top = Top - 1

SortByMark()
for Index in range(5):
    print(Index + 1, Pupils[Index].Name, Pupils[Index].Mark)
An efficient bubble sort on records: compare the Mark fields, swap whole records through Temp, stop after a pass with no swap.

Output

1 Hassan 88
2 Tariq 71
3 Omar 67
4 Mina 45
5 Sara 39
Run and checked before printing

Arrays and records on Paper 4

Short code B4·2·22

Practice for this page of the book: the quiz, flashcards and past-paper questions for its section are listed above.

Workbook 4: Arrays, 2D arrays and records

Short code W4·2 · Practical Programming Task Book

The write-in workbook for this chapter has drills, exam-style practice, trace tables, fix-the-mistake and mark-it-yourself pages. Its full mark schemes and an interactive version arrive here with the chapter.

Starter files

Short code W4·2·K

Data files and skeleton code in Python, VB.NET, Java for this chapter's tasks arrive here with the chapter.

Ask Z about Arrays, 2D arrays and records
Buy ZAK's books — WhatsApp the books desk: Buy the booksPrint or ebook