Skip to content
Book 3: Advanced Theory

Book 3 · Chapter 20

Further Programming

§20.1§20.2Theory. The code is in Book 4Banker · ≈ 54.6 m · ↘B3·20

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

§20.1 Programming paradigms · Object-oriented programming · Declarative programming

Short code B3·20·1

§20.2 File processing and exception handling

Short code B3·20·2

Part A: What a programming paradigm is

Short code B3·20·10

DECLARE Reading : ARRAY[1:5] OF INTEGER
DECLARE Position : INTEGER
DECLARE Count : INTEGER
Reading[1] ← 4
Reading[2] ← 7
Reading[3] ← 4
Reading[4] ← 1
Reading[5] ← 4
Count ← 0
FOR Position ← 1 TO 5
   IF Reading[Position] = 4 THEN
      OUTPUT "4 found at position ", Position
      Count ← Count + 1
   ENDIF
NEXT Position
OUTPUT "Count: ", Count
Imperative: the programmer spells out how, with a variable for the position, a loop, a test and a running count.

Output

4 found at position 1
4 found at position 3
4 found at position 5
Count: 3
Run and checked before printing
# readings as facts
# Runs the program through the CS with ZAK Prolog engine (src/lib/prolog, SWI dialect).
# Cambridge's exam form writes IF / AND / NOT where Prolog writes :- / , / \+
import json, os, subprocess
PROGRAM = "reading(1, 4).\nreading(2, 7).\nreading(3, 4).\nreading(4, 1).\nreading(5, 4).\n"
QUERIES = ["reading(P, 4)."]
eng = os.path.join(os.getcwd(), 'src/lib/prolog/engine.ts')
js = ('import {runProlog, toplevelText} from ' + json.dumps(eng) + ';\n'
      'for (const q of ' + json.dumps(QUERIES) + ') { const {program, result} = runProlog(' + json.dumps(PROGRAM) + ', q);\n'
      ' for (const d of [...program.errors, ...program.warnings]) console.log("DIAGNOSTIC: " + d.message);\n'
      ' console.log("?- " + q); console.log(toplevelText(result)); }')
r = subprocess.run(['npx', 'tsx', '-e', js], capture_output=True, text=True)
print(r.stdout.strip() or r.stderr.strip()[-400:])
Declarative: the same readings as facts. The goal reading(P, 4) asks what matches, and the engine finds every answer.

Output

?- reading(P, 4).
P = 1 ;
P = 3 ;
P = 5.
Run and checked before printing

Low-level programming: addressing modes in code

Short code B3·20·11

100 LDM #201
101 LDD 201
102 LDI 200
103 LDR #2
104 LDX 200
105 END
200 203
201 15
202 8
203 42
Four addressing modes, one load each (LDR #2 sets IX for the indexed load): watch ACC after every line.

Output

OUTPUT:
LDM #201 | ACC=201 | IX=0 |  |
LDD 201 | ACC=15 | IX=0 |  |
LDI 200 | ACC=42 | IX=0 |  |
LDR #2 | ACC=42 | IX=2 |  |
LDX 200 | ACC=8 | IX=2 |  |
END | ACC=8 | IX=2 |  |
Run and checked before printing

Indexed addressing: walking through a list

Short code B3·20·12

100 LDR #0
101 LDX 200
102 ADD 204
103 STO 204
104 INC IX
105 LDD 205
106 INC ACC
107 STO 205
108 CMP #4
109 JPN 101
110 END
200 5
201 9
202 2
203 7
204 0
205 0
Indexed addressing walks the list at 200–203: the same LDX 200 reads a new item each pass because IX goes up by 1. Total ends at 23.

Output

OUTPUT:
LDR #0 | ACC=0 | IX=0 |  |
LDX 200 | ACC=5 | IX=0 |  |
ADD 204 | ACC=5 | IX=0 |  |
STO 204 | ACC=5 | IX=0 | 204=5 |
INC IX | ACC=5 | IX=1 |  |
LDD 205 | ACC=0 | IX=1 |  |
INC ACC | ACC=1 | IX=1 |  |
STO 205 | ACC=1 | IX=1 | 205=1 |
CMP #4 | ACC=1 | IX=1 |  |
JPN 101 | ACC=1 | IX=1 |  |
LDX 200 | ACC=9 | IX=1 |  |
ADD 204 | ACC=14 | IX=1 |  |
STO 204 | ACC=14 | IX=1 | 204=14 |
INC IX | ACC=14 | IX=2 |  |
LDD 205 | ACC=1 | IX=2 |  |
INC ACC | ACC=2 | IX=2 |  |
STO 205 | ACC=2 | IX=2 | 205=2 |
CMP #4 | ACC=2 | IX=2 |  |
JPN 101 | ACC=2 | IX=2 |  |
LDX 200 | ACC=2 | IX=2 |  |
ADD 204 | ACC=16 | IX=2 |  |
STO 204 | ACC=16 | IX=2 | 204=16 |
INC IX | ACC=16 | IX=3 |  |
LDD 205 | ACC=2 | IX=3 |  |
INC ACC | ACC=3 | IX=3 |  |
STO 205 | ACC=3 | IX=3 | 205=3 |
CMP #4 | ACC=3 | IX=3 |  |
JPN 101 | ACC=3 | IX=3 |  |
LDX 200 | ACC=7 | IX=3 |  |
ADD 204 | ACC=23 | IX=3 |  |
STO 204 | ACC=23 | IX=3 | 204=23 |
INC IX | ACC=23 | IX=4 |  |
LDD 205 | ACC=3 | IX=4 |  |
INC ACC | ACC=4 | IX=4 |  |
STO 205 | ACC=4 | IX=4 | 205=4 |
CMP #4 | ACC=4 | IX=4 |  |
JPN 101 | ACC=4 | IX=4 |  |
END | ACC=4 | IX=4 |  |
Run and checked before printing
100 LDR #0
101 LDX 300
102 CMP 305
103 JPN 107
104 LDD 306
105 INC ACC
106 STO 306
107 INC IX
108 LDD 307
109 INC ACC
110 STO 307
111 CMP #5
112 JPN 101
113 END
300 4
301 7
302 4
303 1
304 4
305 4
306 0
307 0
The Mark Ladder's model answer, run: three of the five values at 300–304 equal the target 4, so address 306 ends at 3.

Output

OUTPUT:
LDR #0 | ACC=0 | IX=0 |  |
LDX 300 | ACC=4 | IX=0 |  |
CMP 305 | ACC=4 | IX=0 |  |
JPN 107 | ACC=4 | IX=0 |  |
LDD 306 | ACC=0 | IX=0 |  |
INC ACC | ACC=1 | IX=0 |  |
STO 306 | ACC=1 | IX=0 | 306=1 |
INC IX | ACC=1 | IX=1 |  |
LDD 307 | ACC=0 | IX=1 |  |
INC ACC | ACC=1 | IX=1 |  |
STO 307 | ACC=1 | IX=1 | 307=1 |
CMP #5 | ACC=1 | IX=1 |  |
JPN 101 | ACC=1 | IX=1 |  |
LDX 300 | ACC=7 | IX=1 |  |
CMP 305 | ACC=7 | IX=1 |  |
JPN 107 | ACC=7 | IX=1 |  |
INC IX | ACC=7 | IX=2 |  |
LDD 307 | ACC=1 | IX=2 |  |
INC ACC | ACC=2 | IX=2 |  |
STO 307 | ACC=2 | IX=2 | 307=2 |
CMP #5 | ACC=2 | IX=2 |  |
JPN 101 | ACC=2 | IX=2 |  |
LDX 300 | ACC=4 | IX=2 |  |
CMP 305 | ACC=4 | IX=2 |  |
JPN 107 | ACC=4 | IX=2 |  |
LDD 306 | ACC=1 | IX=2 |  |
INC ACC | ACC=2 | IX=2 |  |
STO 306 | ACC=2 | IX=2 | 306=2 |
INC IX | ACC=2 | IX=3 |  |
LDD 307 | ACC=2 | IX=3 |  |
INC ACC | ACC=3 | IX=3 |  |
STO 307 | ACC=3 | IX=3 | 307=3 |
CMP #5 | ACC=3 | IX=3 |  |
JPN 101 | ACC=3 | IX=3 |  |
LDX 300 | ACC=1 | IX=3 |  |
CMP 305 | ACC=1 | IX=3 |  |
JPN 107 | ACC=1 | IX=3 |  |
INC IX | ACC=1 | IX=4 |  |
LDD 307 | ACC=3 | IX=4 |  |
INC ACC | ACC=4 | IX=4 |  |
STO 307 | ACC=4 | IX=4 | 307=4 |
CMP #5 | ACC=4 | IX=4 |  |
JPN 101 | ACC=4 | IX=4 |  |
LDX 300 | ACC=4 | IX=4 |  |
CMP 305 | ACC=4 | IX=4 |  |
JPN 107 | ACC=4 | IX=4 |  |
LDD 306 | ACC=2 | IX=4 |  |
INC ACC | ACC=3 | IX=4 |  |
STO 306 | ACC=3 | IX=4 | 306=3 |
INC IX | ACC=3 | IX=5 |  |
LDD 307 | ACC=4 | IX=5 |  |
INC ACC | ACC=5 | IX=5 |  |
STO 307 | ACC=5 | IX=5 | 307=5 |
CMP #5 | ACC=5 | IX=5 |  |
JPN 101 | ACC=5 | IX=5 |  |
END | ACC=5 | IX=5 |  |
Run and checked before printing
100 LDR #0
101 LDX 400
102 CMP #0
103 JPN 107
104 LDD 406
105 INC ACC
106 STO 406
107 INC IX
108 LDD 407
109 INC ACC
110 STO 407
111 CMP #6
112 JPN 101
113 END
400 3
401 0
402 0
403 8
404 0
405 2
406 0
407 0
The faded twin's model answer, run: three of the six values at 400–405 are 0, so address 406 ends at 3.

Output

OUTPUT:
LDR #0 | ACC=0 | IX=0 |  |
LDX 400 | ACC=3 | IX=0 |  |
CMP #0 | ACC=3 | IX=0 |  |
JPN 107 | ACC=3 | IX=0 |  |
INC IX | ACC=3 | IX=1 |  |
LDD 407 | ACC=0 | IX=1 |  |
INC ACC | ACC=1 | IX=1 |  |
STO 407 | ACC=1 | IX=1 | 407=1 |
CMP #6 | ACC=1 | IX=1 |  |
JPN 101 | ACC=1 | IX=1 |  |
LDX 400 | ACC=0 | IX=1 |  |
CMP #0 | ACC=0 | IX=1 |  |
JPN 107 | ACC=0 | IX=1 |  |
LDD 406 | ACC=0 | IX=1 |  |
INC ACC | ACC=1 | IX=1 |  |
STO 406 | ACC=1 | IX=1 | 406=1 |
INC IX | ACC=1 | IX=2 |  |
LDD 407 | ACC=1 | IX=2 |  |
INC ACC | ACC=2 | IX=2 |  |
STO 407 | ACC=2 | IX=2 | 407=2 |
CMP #6 | ACC=2 | IX=2 |  |
JPN 101 | ACC=2 | IX=2 |  |
LDX 400 | ACC=0 | IX=2 |  |
CMP #0 | ACC=0 | IX=2 |  |
JPN 107 | ACC=0 | IX=2 |  |
LDD 406 | ACC=1 | IX=2 |  |
INC ACC | ACC=2 | IX=2 |  |
STO 406 | ACC=2 | IX=2 | 406=2 |
INC IX | ACC=2 | IX=3 |  |
LDD 407 | ACC=2 | IX=3 |  |
INC ACC | ACC=3 | IX=3 |  |
STO 407 | ACC=3 | IX=3 | 407=3 |
CMP #6 | ACC=3 | IX=3 |  |
JPN 101 | ACC=3 | IX=3 |  |
LDX 400 | ACC=8 | IX=3 |  |
CMP #0 | ACC=8 | IX=3 |  |
JPN 107 | ACC=8 | IX=3 |  |
INC IX | ACC=8 | IX=4 |  |
LDD 407 | ACC=3 | IX=4 |  |
INC ACC | ACC=4 | IX=4 |  |
STO 407 | ACC=4 | IX=4 | 407=4 |
CMP #6 | ACC=4 | IX=4 |  |
JPN 101 | ACC=4 | IX=4 |  |
LDX 400 | ACC=0 | IX=4 |  |
CMP #0 | ACC=0 | IX=4 |  |
JPN 107 | ACC=0 | IX=4 |  |
LDD 406 | ACC=2 | IX=4 |  |
INC ACC | ACC=3 | IX=4 |  |
STO 406 | ACC=3 | IX=4 | 406=3 |
INC IX | ACC=3 | IX=5 |  |
LDD 407 | ACC=4 | IX=5 |  |
INC ACC | ACC=5 | IX=5 |  |
STO 407 | ACC=5 | IX=5 | 407=5 |
CMP #6 | ACC=5 | IX=5 |  |
JPN 101 | ACC=5 | IX=5 |  |
LDX 400 | ACC=2 | IX=5 |  |
CMP #0 | ACC=2 | IX=5 |  |
JPN 107 | ACC=2 | IX=5 |  |
INC IX | ACC=2 | IX=6 |  |
LDD 407 | ACC=5 | IX=6 |  |
INC ACC | ACC=6 | IX=6 |  |
STO 407 | ACC=6 | IX=6 | 407=6 |
CMP #6 | ACC=6 | IX=6 |  |
JPN 101 | ACC=6 | IX=6 |  |
END | ACC=6 | IX=6 |  |
Run and checked before printing

Relative addressing and relocatable code

Short code B3·20·13

100 LDD 200
101 CMP #0
102 JPE +7
103 ADD #48
104 OUT
105 LDD 200
106 DEC ACC
107 STO 200
108 JMP -8
109 END
200 3
Relative jumps: JPE +7 and JMP -8 are offsets from the instruction's own address. The program outputs 321.

Output

OUTPUT: 321
LDD 200 | ACC=3 | IX=0 |  |
CMP #0 | ACC=3 | IX=0 |  |
JPE +7 | ACC=3 | IX=0 |  |
ADD #48 | ACC=51 | IX=0 |  |
OUT | ACC=51 | IX=0 |  | 3
LDD 200 | ACC=3 | IX=0 |  |
DEC ACC | ACC=2 | IX=0 |  |
STO 200 | ACC=2 | IX=0 | 200=2 |
JMP -8 | ACC=2 | IX=0 |  |
LDD 200 | ACC=2 | IX=0 |  |
CMP #0 | ACC=2 | IX=0 |  |
JPE +7 | ACC=2 | IX=0 |  |
ADD #48 | ACC=50 | IX=0 |  |
OUT | ACC=50 | IX=0 |  | 2
LDD 200 | ACC=2 | IX=0 |  |
DEC ACC | ACC=1 | IX=0 |  |
STO 200 | ACC=1 | IX=0 | 200=1 |
JMP -8 | ACC=1 | IX=0 |  |
LDD 200 | ACC=1 | IX=0 |  |
CMP #0 | ACC=1 | IX=0 |  |
JPE +7 | ACC=1 | IX=0 |  |
ADD #48 | ACC=49 | IX=0 |  |
OUT | ACC=49 | IX=0 |  | 1
LDD 200 | ACC=1 | IX=0 |  |
DEC ACC | ACC=0 | IX=0 |  |
STO 200 | ACC=0 | IX=0 | 200=0 |
JMP -8 | ACC=0 | IX=0 |  |
LDD 200 | ACC=0 | IX=0 |  |
CMP #0 | ACC=0 | IX=0 |  |
JPE +7 | ACC=0 | IX=0 |  |
END | ACC=0 | IX=0 |  |
Run and checked before printing
500 LDD 600
501 CMP #0
502 JPE +7
503 ADD #48
504 OUT
505 LDD 600
506 DEC ACC
507 STO 600
508 JMP -8
509 END
600 3
The same program loaded at 500 instead of 100. The jumps still land in the right place; only the direct data addresses had to change (200 → 600).

Output

OUTPUT: 321
LDD 600 | ACC=3 | IX=0 |  |
CMP #0 | ACC=3 | IX=0 |  |
JPE +7 | ACC=3 | IX=0 |  |
ADD #48 | ACC=51 | IX=0 |  |
OUT | ACC=51 | IX=0 |  | 3
LDD 600 | ACC=3 | IX=0 |  |
DEC ACC | ACC=2 | IX=0 |  |
STO 600 | ACC=2 | IX=0 | 600=2 |
JMP -8 | ACC=2 | IX=0 |  |
LDD 600 | ACC=2 | IX=0 |  |
CMP #0 | ACC=2 | IX=0 |  |
JPE +7 | ACC=2 | IX=0 |  |
ADD #48 | ACC=50 | IX=0 |  |
OUT | ACC=50 | IX=0 |  | 2
LDD 600 | ACC=2 | IX=0 |  |
DEC ACC | ACC=1 | IX=0 |  |
STO 600 | ACC=1 | IX=0 | 600=1 |
JMP -8 | ACC=1 | IX=0 |  |
LDD 600 | ACC=1 | IX=0 |  |
CMP #0 | ACC=1 | IX=0 |  |
JPE +7 | ACC=1 | IX=0 |  |
ADD #48 | ACC=49 | IX=0 |  |
OUT | ACC=49 | IX=0 |  | 1
LDD 600 | ACC=1 | IX=0 |  |
DEC ACC | ACC=0 | IX=0 |  |
STO 600 | ACC=0 | IX=0 | 600=0 |
JMP -8 | ACC=0 | IX=0 |  |
LDD 600 | ACC=0 | IX=0 |  |
CMP #0 | ACC=0 | IX=0 |  |
JPE +7 | ACC=0 | IX=0 |  |
END | ACC=0 | IX=0 |  |
Run and checked before printing

Imperative (procedural) programming

Short code B3·20·14

DECLARE Reading : ARRAY[1:5] OF INTEGER
DECLARE Position : INTEGER
DECLARE Count : INTEGER
Reading[1] ← 4
Reading[2] ← 7
Reading[3] ← 4
Reading[4] ← 1
Reading[5] ← 4
Count ← 0
FOR Position ← 1 TO 5
   IF Reading[Position] = 4 THEN
      OUTPUT "4 found at position ", Position
      Count ← Count + 1
   ENDIF
NEXT Position
OUTPUT "Count: ", Count
Imperative: the programmer spells out how, with a variable for the position, a loop, a test and a running count.

Output

4 found at position 1
4 found at position 3
4 found at position 5
Count: 3
Run and checked before printing

Classes and objects

Short code B3·20·15

Output

LHR-207 1200g standard
KHI-118 300g standard
FALSE TRUE
Run and checked before printing

Encapsulation: PRIVATE, PUBLIC, getters and setters

Short code B3·20·16

DECLARE P1 : Parcel
P1 ← NEW Parcel("LHR-207", 1200)
P1.SetGrams(-3)
OUTPUT P1.GetGrams()
P1.SetGrams(1150)
OUTPUT P1.GetGrams()
The setter refuses a weight of −3, so the parcel keeps 1200; only methods of the class change Grams.

Output

1200
1150
Run and checked before printing
DECLARE P1 : Parcel
P1 ← NEW Parcel("LHR-207", 1200)
OUTPUT P1.Grams
Reading a PRIVATE attribute from outside the class is refused before the program even runs.

Output

ERROR: Line 33: Grams is a PRIVATE attribute of Parcel — it can only be used inside the class; add a public getter/setter method
Run and checked before printing

Inheritance

Short code B3·20·17

CLASS ExpressParcel INHERITS Parcel
   PRIVATE Deadline : STRING
   PUBLIC PROCEDURE NEW(GivenCode : STRING, GivenGrams : INTEGER, GivenDeadline : STRING)
      SUPER.NEW(GivenCode, GivenGrams)
      Deadline ← GivenDeadline
   ENDPROCEDURE
   PUBLIC FUNCTION GetDeadline() RETURNS STRING
      RETURN Deadline
   ENDFUNCTION
   PUBLIC PROCEDURE ShowLabel()
      OUTPUT GetCode(), " ", GetGrams(), "g EXPRESS by ", Deadline
   ENDPROCEDURE
ENDCLASS
DECLARE P3 : ExpressParcel
P3 ← NEW ExpressParcel("ISB-031", 450, "10:00")
P3.ShowLabel()
P3.SetGrams(500)
P3.ShowLabel()
The subclass adds one attribute and replaces one method; GetCode(), GetGrams() and SetGrams() come from Parcel for free.

Output

ISB-031 450g EXPRESS by 10:00
ISB-031 500g EXPRESS by 10:00
Run and checked before printing

Polymorphism and overloading

Short code B3·20·18

DECLARE Round : ARRAY[1:3] OF Parcel
DECLARE i : INTEGER
Round[1] ← NEW Parcel("LHR-207", 1200)
Round[2] ← NEW ExpressParcel("ISB-031", 450, "10:00")
Round[3] ← NEW FragileParcel("KHI-118", 300, "this way up")
FOR i ← 1 TO 3
   Round[i].ShowLabel()
NEXT i
One loop, one call, three different labels: each object runs its own class's ShowLabel().

Output

LHR-207 1200g standard
ISB-031 450g EXPRESS by 10:00
KHI-118 300g FRAGILE: this way up
Run and checked before printing
public class Main {
    // two methods with the same name: the arguments decide which one runs
    static int area(int side) {
        return side * side;
    }
    static int area(int length, int width) {
        return length * width;
    }
    public static void main(String[] args) {
        System.out.println(area(3));
        System.out.println(area(3, 4));
    }
}
Overloading in Java (Book 4's languages): one name, two parameter lists.

Output

9
12
Run and checked before printing

Containment

Short code B3·20·19

Output

TRUE
TRUE
FALSE
1650
Run and checked before printing

Designing classes from a scenario

Short code B3·20·20

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

Declarative programming: facts and goals

Short code B3·20·21

# the coding club: goals on facts
# Runs the program through the CS with ZAK Prolog engine (src/lib/prolog, SWI dialect).
# Cambridge's exam form writes IF / AND / NOT where Prolog writes :- / , / \+
import json, os, subprocess
PROGRAM = "course(python).\ncourse(robotics).\ncourse(webdesign).\ncourse(gamedesign).\nstudent(sana).\nstudent(bilal).\nstudent(hira).\ncompleted(sana, python).\ncompleted(hira, python).\ncompleted(hira, robotics).\nneeds(robotics, python).\nneeds(gamedesign, robotics).\nneeds(webdesign, python).\n"
QUERIES = ["completed(hira, X).", "completed(X, python).", "needs(gamedesign, robotics).", "student(zara)."]
eng = os.path.join(os.getcwd(), 'src/lib/prolog/engine.ts')
js = ('import {runProlog, toplevelText} from ' + json.dumps(eng) + ';\n'
      'for (const q of ' + json.dumps(QUERIES) + ') { const {program, result} = runProlog(' + json.dumps(PROGRAM) + ', q);\n'
      ' for (const d of [...program.errors, ...program.warnings]) console.log("DIAGNOSTIC: " + d.message);\n'
      ' console.log("?- " + q); console.log(toplevelText(result)); }')
r = subprocess.run(['npx', 'tsx', '-e', js], capture_output=True, text=True)
print(r.stdout.strip() or r.stderr.strip()[-400:])
The coding club's facts, with the goals from the spread: every answer the engine gives, in the order it finds them.

Output

?- completed(hira, X).
X = python ;
X = robotics.
?- completed(X, python).
X = sana ;
X = hira ;
false.
?- needs(gamedesign, robotics).
true.
?- student(zara).
false.
Run and checked before printing

Writing rules

Short code B3·20·22

# the coding club: the ready_for rule
# Runs the program through the CS with ZAK Prolog engine (src/lib/prolog, SWI dialect).
# Cambridge's exam form writes IF / AND / NOT where Prolog writes :- / , / \+
import json, os, subprocess
PROGRAM = "course(python).\ncourse(robotics).\ncourse(webdesign).\ncourse(gamedesign).\nstudent(sana).\nstudent(bilal).\nstudent(hira).\ncompleted(sana, python).\ncompleted(hira, python).\ncompleted(hira, robotics).\nneeds(robotics, python).\nneeds(gamedesign, robotics).\nneeds(webdesign, python).\nready_for(S, C) :- student(S), needs(C, P), completed(S, P), \\+ completed(S, C).\n"
QUERIES = ["ready_for(sana, C).", "ready_for(hira, C).", "ready_for(bilal, C)."]
eng = os.path.join(os.getcwd(), 'src/lib/prolog/engine.ts')
js = ('import {runProlog, toplevelText} from ' + json.dumps(eng) + ';\n'
      'for (const q of ' + json.dumps(QUERIES) + ') { const {program, result} = runProlog(' + json.dumps(PROGRAM) + ', q);\n'
      ' for (const d of [...program.errors, ...program.warnings]) console.log("DIAGNOSTIC: " + d.message);\n'
      ' console.log("?- " + q); console.log(toplevelText(result)); }')
r = subprocess.run(['npx', 'tsx', '-e', js], capture_output=True, text=True)
print(r.stdout.strip() or r.stderr.strip()[-400:])
The ready_for rule: Sana is ready for two courses, Hira for two and Bilal for none.

Output

?- ready_for(sana, C).
C = robotics ;
C = webdesign.
?- ready_for(hira, C).
C = gamedesign ;
C = webdesign ;
false.
?- ready_for(bilal, C).
false.
Run and checked before printing
# the car park rule
# Runs the program through the CS with ZAK Prolog engine (src/lib/prolog, SWI dialect).
# Cambridge's exam form writes IF / AND / NOT where Prolog writes :- / , / \+
import json, os, subprocess
PROGRAM = "vehicle(car).\nvehicle(van).\nvehicle(coach).\nzone(east).\nzone(north).\nzone(west).\nsize(car, small).\nsize(van, medium).\nsize(coach, large).\nfits(east, small).\nfits(east, medium).\nfits(north, small).\nfits(west, small).\nfits(west, medium).\nfits(west, large).\nfull(east).\ncan_park(V, Z) :- vehicle(V), zone(Z), size(V, S), fits(Z, S), \\+ full(Z).\n"
QUERIES = ["can_park(car, Z).", "can_park(coach, Z).", "can_park(V, east)."]
eng = os.path.join(os.getcwd(), 'src/lib/prolog/engine.ts')
js = ('import {runProlog, toplevelText} from ' + json.dumps(eng) + ';\n'
      'for (const q of ' + json.dumps(QUERIES) + ') { const {program, result} = runProlog(' + json.dumps(PROGRAM) + ', q);\n'
      ' for (const d of [...program.errors, ...program.warnings]) console.log("DIAGNOSTIC: " + d.message);\n'
      ' console.log("?- " + q); console.log(toplevelText(result)); }')
r = subprocess.run(['npx', 'tsx', '-e', js], capture_output=True, text=True)
print(r.stdout.strip() or r.stderr.strip()[-400:])
The faded twin's car park: the rule run on every vehicle.

Output

?- can_park(car, Z).
Z = north ;
Z = west.
?- can_park(coach, Z).
Z = west.
?- can_park(V, east).
false.
Run and checked before printing

How a goal is satisfied: matching and backtracking

Short code B3·20·23

# the coding club: the ready_for rule
# Runs the program through the CS with ZAK Prolog engine (src/lib/prolog, SWI dialect).
# Cambridge's exam form writes IF / AND / NOT where Prolog writes :- / , / \+
import json, os, subprocess
PROGRAM = "course(python).\ncourse(robotics).\ncourse(webdesign).\ncourse(gamedesign).\nstudent(sana).\nstudent(bilal).\nstudent(hira).\ncompleted(sana, python).\ncompleted(hira, python).\ncompleted(hira, robotics).\nneeds(robotics, python).\nneeds(gamedesign, robotics).\nneeds(webdesign, python).\nready_for(S, C) :- student(S), needs(C, P), completed(S, P), \\+ completed(S, C).\n"
QUERIES = ["ready_for(sana, C).", "ready_for(hira, C).", "ready_for(bilal, C)."]
eng = os.path.join(os.getcwd(), 'src/lib/prolog/engine.ts')
js = ('import {runProlog, toplevelText} from ' + json.dumps(eng) + ';\n'
      'for (const q of ' + json.dumps(QUERIES) + ') { const {program, result} = runProlog(' + json.dumps(PROGRAM) + ', q);\n'
      ' for (const d of [...program.errors, ...program.warnings]) console.log("DIAGNOSTIC: " + d.message);\n'
      ' console.log("?- " + q); console.log(toplevelText(result)); }')
r = subprocess.run(['npx', 'tsx', '-e', js], capture_output=True, text=True)
print(r.stdout.strip() or r.stderr.strip()[-400:])
The ready_for rule: Sana is ready for two courses, Hira for two and Bilal for none.

Output

?- ready_for(sana, C).
C = robotics ;
C = webdesign.
?- ready_for(hira, C).
C = gamedesign ;
C = webdesign ;
false.
?- ready_for(bilal, C).
false.
Run and checked before printing

Part B: Processing files

Short code B3·20·24

DECLARE Line : STRING
OPENFILE "Visits.txt" FOR APPEND
WRITEFILE "Visits.txt", "11/10/2027 Usman"
CLOSEFILE "Visits.txt"
OPENFILE "Visits.txt" FOR READ
WHILE NOT EOF("Visits.txt")
   READFILE "Visits.txt", Line
   OUTPUT Line
ENDWHILE
CLOSEFILE "Visits.txt"
A serial file grows at the end: APPEND keeps the two visits already there and adds the new one after them.

Output

10/10/2027 Ayesha
10/10/2027 Omar
11/10/2027 Usman
Run and checked before printing

Adding a record to a sequential file

Short code B3·20·25

Output

Asma
Danish
Kamran
Laila
Tariq
Run and checked before printing

Random files: SEEK, GETRECORD and PUTRECORD

Short code B3·20·26

DECLARE Tool : TTool
DECLARE Position : INTEGER
Position ← 3
OPENFILE "Tools.dat" FOR RANDOM
CALL AddTestTools("Tools.dat")   // five test records, not shown
SEEK "Tools.dat", Position
GETRECORD "Tools.dat", Tool
OUTPUT Tool.Name, " on loan: ", Tool.OnLoan
Tool.OnLoan ← TRUE
SEEK "Tools.dat", Position
PUTRECORD "Tools.dat", Tool
SEEK "Tools.dat", Position
GETRECORD "Tools.dat", Tool
OUTPUT Tool.Name, " on loan: ", Tool.OnLoan
CLOSEFILE "Tools.dat"
Lending tool 3: read the record at address 3, change one field in memory, write the record back to the same address.

Output

Sander on loan: FALSE
Sander on loan: TRUE
Run and checked before printing

Exceptions and why they must be handled

Short code B3·20·27

DECLARE Tool : TTool
DECLARE Position : INTEGER
OPENFILE "Tools.dat" FOR RANDOM
CALL AddTestTools("Tools.dat")   // five test records, not shown
FOR Position ← 4 TO 6
   TRY
      SEEK "Tools.dat", Position
      GETRECORD "Tools.dat", Tool
      OUTPUT Position, ": ", Tool.Name
   EXCEPT
      OUTPUT Position, ": no record here - skipped"
   ENDTRY
NEXT Position
CLOSEFILE "Tools.dat"
OUTPUT "Report finished"
Illustrative only. TRY … EXCEPT … ENDTRY is not in the 9618 pseudocode guide. There is no record at address 6; the handler reports it and the program carries on to the end.

Output

4: Saw
5: Wheelbarrow
6: no record here - skipped
Report finished
Run and checked before printing
readings = ["21", "2O", "19"]
total = 0
for text in readings:
    try:
        total = total + int(text)
    except ValueError:
        print("Not a whole number:", text)
print("Total", total)
The same idea in Python (Book 4 Ch P4.9): int("2O") raises a ValueError, the handler reports it, and the loop goes on.

Output

Not a whole number: 2O
Total 40
Run and checked before printing

When to use exception handling

Short code B3·20·28

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

Past-paper practice

Short code B3·20·90

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

Workbook 3: Further Programming

Short code W3·20 · Advanced Theory Workbook

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.

Ask Z about Further Programming
Buy ZAK's books — WhatsApp the books desk: Buy the booksPrint or ebook