Book 4 · Chapter P4.2
Arrays, 2D arrays and records
B4·2This 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.
For the whole chapter
- Topic pageData Types and Structures
B4·2·T - QuizData Types & Structures
B4·2·Q1 - LabData Structures Playground
B4·2·X1 - LabBubble sort & linear search
B4·2·X2 - LabRecord & file tasks
B4·2·X3
§10.1 Data types and records
Short code B4·2·1
- FlashcardsFlashcards §10.1–10.2: Data types, records & arrays
B4·2·F1 - Past-paper questionsPast-paper questions §10.1 (data-types-and-records)
B4·2·1
§10.2 Arrays
Short code B4·2·2
- FlashcardsFlashcards §10.1–10.2: Data types, records & arrays
B4·2·F1 - FlashcardsFlashcards §10.2–10.4: Standard algorithms & ADT operations
B4·2·F2 - Past-paper questionsPast-paper questions §10.2 (arrays)
B4·2·2
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])Output
Total rain: 18 Day 1 had 4
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])Output
10 elements First: Ayesha 72 Last: Zain 0
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()Stock = 12, 4, 30, 9, 15, 10, 2, 22.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))Output
5 0
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)Output
Total 168 Mean 24 Hottest: day 4 at 30 Coolest: day 3 at 19 Days above the mean: 4
Linear search in code
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"))Output
C7 is at index 3 Z1 is at index -1
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]]
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)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
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)Output
Coral Reefs 3 4.5 C On loan, due 2027-03-28
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)Variable.Field.Output
Hassan of form B scored 88
from dataclasses import dataclass
@dataclass
class Pupil:
Name: str = ""
Form: str = ""
Mark: int = 0
Top = Pupil("Hassan", "B", 88)
print(Top.Name, Top.Mark)dataclass: the field list with types is the declaration, and the constructor is written for you.Output
Hassan 88
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 ModuleB = A copies a Structure, so changing B leaves A alone.Output
88 50
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)B = A copies the reference, so A and B are one record.Output
50 50
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)Mark field of each element to list the passes and work out the mean.Output
Hassan 88 Omar 67 Tariq 71 Mean mark 62
Searching an array of records
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)Name), return the index, then use that index to read the other fields.Output
Sara: form C mark 39 Zoe: not found
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)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
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.


