Skip to content
9618Paper 4 · Practical§20.1, §20.2

20. Further Programming

Programming paradigms (low-level, imperative, OOP, declarative), full object-oriented programming (classes, inheritance, polymorphism, encapsulation), file processing with random-access files, and exception handling.

Statometer96BankerNext Paper 495%
Marks a paper63.1 · 84%Rank#1 of 8 · #1 on P4Trend · last 12Oct/Nov 24 · 41: 56 marksOct/Nov 24 · 42: 75 marksOct/Nov 24 · 43: 56 marksMay/Jun 25 · 41: 75 marksMay/Jun 25 · 42: 75 marksMay/Jun 25 · 43: 55 marksOct/Nov 25 · 41: 75 marksOct/Nov 25 · 42: 49 marksOct/Nov 25 · 43: 75 marksMay/Jun 26 · 41: 75 marksMay/Jun 26 · 42: 57 marksMay/Jun 26 · 43: 50 marks
9 in 10 chance in the next paper

Everything for this topic — study hub

A2 Level · 9618 · Paper 4

Statometer — what 64 real papers say about this topic and each of its 4 syllabus bullets

Banker · #1 of 8 in A2 Level · recomputed with every new session

96BANKER
Banker#1 of 8 in A2 Level#1 on Paper 4 Steady

Set in nearly every paper and worth a big slice of it — revise first, expect it.

Next Paper 4
95%
9 in 10 chance it is set
Marks a paper
63.1 / 75
84% of Paper 4 · fair share 50%
Appeared in
32 / 32
Paper 4 sittings 20212026
Last set
May/Jun 2026
9618/43 · Q2 · 29 marks · 11-series streak
Marks in each of the last 12 Paper 4 sittingsOct/Nov 24May/Jun 26
Oct/Nov 24 · 41: 56 marksOct/Nov 24 · 42: 75 marksOct/Nov 24 · 43: 56 marksMay/Jun 25 · 41: 75 marksMay/Jun 25 · 42: 75 marksMay/Jun 25 · 43: 55 marksOct/Nov 25 · 41: 75 marksOct/Nov 25 · 42: 49 marksOct/Nov 25 · 43: 75 marksMay/Jun 26 · 41: 75 marksMay/Jun 26 · 42: 57 marksMay/Jun 26 · 43: 50 marks

What the papers say

  • Set in 32 of 32 Paper 4 sittings on the current syllabus — treat it as certain.
  • Worth about 63.1 marks a paper (84% of Paper 4, 1.7× its fair share).
  • Also turns up in Paper 3 (100% of sittings, ~14.6 marks) — usually inside a scenario question.
  • Last set May/Jun 2026 · 9618/43 · Q2 for 29 marks — in the most recent series.
  • Set in each of the last 11 series without a miss.
  • Steady at around 64.3 marks a paper year on year.
  • Lives on “Write” and “Amend” — 69% of its questions: you must produce something — code, a diagram, a table — practise doing it, not reading it.
  • 72% of its questions are set out as code, pseudocode or a table to complete.
  • Most of its marks (83%) come in extended questions of 12+ marks — plan the answer before writing.
  • Its biggest question so far: 49 marks (May/Jun 2023 · 9618/32 · Q9).
  • Inside the topic, §20.1 Object-oriented programming carries the most marks (72%) and §20.1 Declarative programming the least (4%).
  • §20.1 Declarative programming has not been asked for 11 series — the bullet most likely to be “due”.
  • It is examined almost entirely as AO3 (Design, program & evaluate, 80%) — you must build it — write the pseudocode or program, design the structure.
  • The examiner has commented on 77 of its questions — read “What the examiner said” before you practise.
  • The single biggest share of Paper 4 among its 2 topics.

Command words

Share of questions using the word (a question can use several). What each wants →

Question shapes

  • ≤ 6 mk30
  • 7–9 mk27
  • 10–12 mk4
  • 13–15 mk1
  • 16+ mk75

Average 17.8 marks a question · 15% with a figure or table · 72% with code · biggest 49 marks

Assessment objectives — how it is examined

Every part of every current-syllabus question filed under Cambridge's AO1 / AO2 / AO3 (from its command word and what it asks you to do), so you know whether this topic pays for definitions, for applying, or for judging and building.

  • AO1 Knowledge & understanding
  • AO2 Apply & analyse
  • AO3 Design, program & evaluate

Paper 4 as a whole

Paper 4SyllabusMeasured
AO1 Knowledge & understanding0%0%
AO2 Apply & analyse0%1%
AO3 Design, program & evaluate100%99%

Syllabus = Cambridge's grid; measured = the bank's current-syllabus papers.

Inside the topic — every syllabus bullet, measured

Each part of each question is filed under the bullet it examines; the numbers are per Paper 4 sitting, exactly like the topic's. Open a bullet for its own Statometer.

  • 20.1Programming paradigms#6 of 7 on Paper 4Occasional · 1019% next paper0.4 marks6/32 sittings May/Jun 2025

    Rotated in occasionally — the bullet students skip and then meet.Syllabus: what a paradigm is; low-level code with immediate, direct, indirect, indexed and relative addressing; imperative code with constructs, procedures and functions

    Next Paper 4
    19%
    1 in 5 or less
    Marks a paper
    0.4
    1% of the paper · 5% of the topic
    Asked in
    6 / 32
    Paper 4 sittings · 18 questions
    Last asked
    May/Jun 2025
    9618/42 · Q2 · 1 marks · 2 series ago
    • Asked in only 6 of 32 Paper 4 sittings — rare, which is exactly why it catches candidates out.
    • About 0.4 marks a paper (1% of Paper 4; 5% of the topic's marks across its 4 bullets).
    • Last asked May/Jun 2025 · 9618/42 · Q2 (1 marks), 2 seriess ago.
    • Easing: 1.2 → 0.3 marks a paper.
    • Usually “Write”: you must produce something — code, a diagram, a table — practise doing it, not reading it.
    • Biggest chunk of marks so far: 10 in May/Jun 2022 · 9618/31 · Q9.
    • It is examined as a mix: AO1 42%, AO2 34%, AO3 24% — definitions and descriptions in syllabus words score.
    Last 12 sittings Easing
    Oct/Nov 24 · 41: 0 marksOct/Nov 24 · 42: 0 marksOct/Nov 24 · 43: 0 marksMay/Jun 25 · 41: 0 marksMay/Jun 25 · 42: 1 marksMay/Jun 25 · 43: 0 marksOct/Nov 25 · 41: 0 marksOct/Nov 25 · 42: 0 marksOct/Nov 25 · 43: 0 marksMay/Jun 26 · 41: 0 marksMay/Jun 26 · 42: 0 marksMay/Jun 26 · 43: 0 marks

    Assessment objectives

    • AO1 Knowledge & understanding
    • AO2 Apply & analyse
    • AO3 Design, program & evaluate
    • Write50%
    • Show22%
    • State17%
    • Describe17%
  • 20.1Object-oriented programming#1 of 7 on Paper 4Banker · 9895% next paper45.1 marks32/32 sittings May/Jun 2026

    Asked in nearly every paper — the bullet to know cold.Syllabus: objects, attributes, methods, classes, inheritance, polymorphism, containment, encapsulation, getters and setters; designing classes and writing OOP code

    Next Paper 4
    95%
    9 in 10
    Marks a paper
    45.1
    60% of the paper · 72% of the topic
    Asked in
    32 / 32
    Paper 4 sittings · 94 questions
    Last asked
    May/Jun 2026
    9618/43 · Q2 · 21.5 marks · 11-series streak
    • Asked in 32 of 32 Paper 4 sittings — nearly every paper.
    • About 45.1 marks a paper (60% of Paper 4; 72% of the topic's marks across its 4 bullets).
    • Last asked May/Jun 2026 · 9618/43 · Q2 (21.5 marks) — in the most recent series.
    • Asked in each of the last 11 series.
    • Rising: 39.8 → 45.8 marks a paper.
    • Usually “Write”: you must produce something — code, a diagram, a table — practise doing it, not reading it.
    • Biggest chunk of marks so far: 31 in May/Jun 2023 · 9618/41 · Q2.
    • It is examined almost entirely as AO3 (Design, program & evaluate, 90%) — you must build it — write the pseudocode or program, design the structure.
    Last 12 sittings Rising
    Oct/Nov 24 · 41: 36 marksOct/Nov 24 · 42: 34.5 marksOct/Nov 24 · 43: 36 marksMay/Jun 25 · 41: 46 marksMay/Jun 25 · 42: 55 marksMay/Jun 25 · 43: 41 marksOct/Nov 25 · 41: 48 marksOct/Nov 25 · 42: 37.5 marksOct/Nov 25 · 43: 61 marksMay/Jun 26 · 41: 53.5 marksMay/Jun 26 · 42: 43 marksMay/Jun 26 · 43: 38.5 marks

    Assessment objectives

    • AO1 Knowledge & understanding
    • AO2 Apply & analyse
    • AO3 Design, program & evaluate
    • Write82%
    • Amend27%
    • Complete14%
    • Name11%
  • 20.1Declarative programming#7 of 7 on Paper 4Occasional · 26% next paper0 marks0/32 sittings May/Jun 2026

    Rotated in occasionally — the bullet students skip and then meet.Syllabus: solving problems by writing facts and rules; writing code that satisfies a goal

    Next Paper 4
    6%
    1 in 5 or less
    Marks a paper
    0
    0% of the paper · 4% of the topic
    Asked in
    0 / 32
    Paper 4 sittings · 13 questions
    Last asked
    May/Jun 2026
    9618/31 · Q11 · 8 marks · 11 series ago
    • Asked in only 0 of 32 Paper 4 sittings — rare, which is exactly why it catches candidates out.
    • About 0 marks a paper (0% of Paper 4; 4% of the topic's marks across its 4 bullets).
    • Not asked since May/Jun 2026 · 9618/31 · Q11 — 11 series ago. Bullets rotate inside a topic more than topics do: this one is due a turn.
    • Usually “Write”: you must produce something — code, a diagram, a table — practise doing it, not reading it.
    • Biggest chunk of marks so far: 9 in May/Jun 2024 · 9618/32 · Q10.
    • It is examined almost entirely as AO2 (Apply & analyse, 93%) — you must apply it to the given data or scenario — work it out, trace it, explain it in context.
    Last 12 sittings Steady
    Oct/Nov 24 · 41: 0 marksOct/Nov 24 · 42: 0 marksOct/Nov 24 · 43: 0 marksMay/Jun 25 · 41: 0 marksMay/Jun 25 · 42: 0 marksMay/Jun 25 · 43: 0 marksOct/Nov 25 · 41: 0 marksOct/Nov 25 · 42: 0 marksOct/Nov 25 · 43: 0 marksMay/Jun 26 · 41: 0 marksMay/Jun 26 · 42: 0 marksMay/Jun 26 · 43: 0 marks

    Assessment objectives

    • AO1 Knowledge & understanding
    • AO2 Apply & analyse
    • AO3 Design, program & evaluate
    • Write77%
    • Describe23%
    • Identify23%
    • Program23%
  • 20.2File processing and exception handling#3 of 7 on Paper 4Banker · 8395% next paper8.7 marks32/32 sittings May/Jun 2026

    Asked in nearly every paper — the bullet to know cold.Syllabus: opening (read/write/append) and closing files; reading and writing records; serial, sequential and random files; when and how to use exception handling

    Next Paper 4
    95%
    9 in 10
    Marks a paper
    8.7
    12% of the paper · 19% of the topic
    Asked in
    32 / 32
    Paper 4 sittings · 64 questions
    Last asked
    May/Jun 2026
    9618/43 · Q2 · 3.5 marks · 11-series streak
    • Asked in 32 of 32 Paper 4 sittings — nearly every paper.
    • About 8.7 marks a paper (12% of Paper 4; 19% of the topic's marks across its 4 bullets).
    • Last asked May/Jun 2026 · 9618/43 · Q2 (3.5 marks) — in the most recent series.
    • Asked in each of the last 11 series.
    • Rising: 7.5 → 8.7 marks a paper.
    • Usually “Write”: you must produce something — code, a diagram, a table — practise doing it, not reading it.
    • Biggest chunk of marks so far: 22 in May/Jun 2025 · 9618/41 · Q2.
    • It is examined mostly as AO3 (Design, program & evaluate, 66%) — you must build it — write the pseudocode or program, design the structure.
    Last 12 sittings Rising
    Oct/Nov 24 · 41: 8 marksOct/Nov 24 · 42: 6.5 marksOct/Nov 24 · 43: 8 marksMay/Jun 25 · 41: 22 marksMay/Jun 25 · 42: 16 marksMay/Jun 25 · 43: 6 marksOct/Nov 25 · 41: 13 marksOct/Nov 25 · 42: 7.5 marksOct/Nov 25 · 43: 8 marksMay/Jun 26 · 41: 14.5 marksMay/Jun 26 · 42: 6 marksMay/Jun 26 · 43: 3.5 marks

    Assessment objectives

    • AO1 Knowledge & understanding
    • AO2 Apply & analyse
    • AO3 Design, program & evaluate
    • Write66%
    • Amend25%
    • Describe17%
    • State16%

15% of the topic's marks sit in question parts that belong to another topic (scenario questions cross sections) or that no bullet claims; they count for the topic, not for a bullet.

Marks a paper, year by year

212223242526

By exam series

  • May/Jun18/18 · 65.6 mk
  • Oct/Nov14/14 · 56 mk

Across papers: Paper 3 100% of sittings, ~14.6 marks · Paper 4 100% of sittings, ~63.1 marks.

What you need to know4syllabus §20.1, §20.2

  1. 20.1Programming paradigmswhat a paradigm is; low-level code with immediate, direct, indirect, indexed and relative addressing; imperative code with constructs, procedures and functions
  2. 20.1Object-oriented programmingobjects, attributes, methods, classes, inheritance, polymorphism, containment, encapsulation, getters and setters; designing classes and writing OOP code
  3. 20.1Declarative programmingsolving problems by writing facts and rules; writing code that satisfies a goal
  4. 20.2File processing and exception handlingopening (read/write/append) and closing files; reading and writing records; serial, sequential and random files; when and how to use exception handling

Video lectures11ZAK's YouTube channel · play here

  • A22023260 views

  • A2Urdu2021894 views

  • ASA2Urdu20201.2K views

  • ASA220206.7K views

  • ASA220201.8K views

  • ASA22020851 views

Infographics2draw these the way the examiner expects · download as PNG

OOP: classes, inheritance, polymorphism & encapsulationA class is a template; an object is one instance. Inheritance reuses a parent class; polymorphism lets achild override it.Pet− Name : STRING+ NEW(GivenName)+ GetName() : STRING+ Speak()Cat− Breed : STRING+ NEW(GivenName, GivenBreed)+ Speak() ← overridesINHERITSOwner− Pets : ARRAY OF Pethas-aTerms — use them exactlyTermMeaningClassblueprint: attributes + methodsObjectinstance created with NEWAttributedata inside an objectMethodprocedure/function in a classConstructorNEW: sets initial attribute valuesEncapsulationPRIVATE data, PUBLIC get/set methodsInheritancechild gets parent's membersPolymorphismsame method name, different behaviourContainmentan object holds other objectsGetter / setterread / validate-and-write an attributeMyCat ← NEW Cat("Kitty", "Shorthair")CALL MyCat.Speak() → Cat's version runsSUPER.NEW(GivenName) calls the parent constructor.Why encapsulate? Data can only change throughmethods that validate it — fewer bugs, easier change.Class diagram: name on top, attributes, then methods. − private, + public. Hollow arrow = inherits; diamond = contains.Paper 4: write it in Python / VB.NET / Java with private attributes (__name / Private / private) and public get/set.cswithzak.com

OOP: classes, inheritance & polymorphism

A2
Programming paradigms, file processing & exception handlingA paradigm is a style of programming. The same problem can be solved in each — know one language and onefeature of each.Low-levelassembly / machine codeLDD 200 / ADD #1 / STO 200 — direct control of registers and memoryImperative (procedural)Python, C, Pascal, VBsequence, selection, iteration, procedures — step-by-step HOWObject-orientedJava, Python, VB.NET, C++classes, objects, inheritance, polymorphism, encapsulationDeclarativeSQL, Prolog, Haskelldescribe WHAT you want; facts + rules or queries — no loops writtenException handlingtry: n = int(input("Age: "))except ValueError: print("Not a number")finally: print("done") # always runsAn exception = a run-time error the program can catch instead ofcrashing: bad input, file not found, division by zero, bad index.VB.NET: Try / Catch / Finally · Java: try / catch / finally.Catch specific types first; use finally to close files regardless.File processing (Paper 4)# text file, line by linewith open("marks.txt") as f: for line in f: name, mark = line.strip().split(",")# random-access binary file of recordsf.seek(recordNo * RECORD_SIZE)f.write(pickle.dumps(rec)) # or structText files: open, read/write line, append, close.Random files: seek to record × size, then read/write.cswithzak.com

Paradigms, files & exception handling

A2

Browse all infographics →

Key terms13use these exact words in the exam

paradigmdeclarativeclassobjectconstructorinheritancepolymorphismencapsulationcontainmentgettersetterrandom fileexception

Dotted terms are defined in the glossary.

Code help5referenced to the Cambridge pseudocode guide

Guide §10: the Pet / Cat classes, fully runnable

pseudocode §10.1–10.2 Run in Playground
CLASS Pet
PRIVATE Name : STRING
PUBLIC PROCEDURE NEW(GivenName : STRING)
Name GivenName
ENDPROCEDURE
PUBLIC FUNCTION GetName() RETURNS STRING
RETURN Name
ENDFUNCTION
PUBLIC PROCEDURE Speak()
OUTPUT Name, " makes a noise"
ENDPROCEDURE
ENDCLASS
CLASS Cat INHERITS Pet
PRIVATE Breed : STRING
PUBLIC PROCEDURE NEW(GivenName : STRING, GivenBreed : STRING)
SUPER.NEW(GivenName)
Breed GivenBreed
ENDPROCEDURE
PUBLIC PROCEDURE Speak() // polymorphism: overrides Pet.Speak
OUTPUT GetName(), " the ", Breed, " says Meow"
ENDPROCEDURE
ENDCLASS
DECLARE P : Pet
DECLARE MyCat : Cat
P NEW Pet("Rex")
MyCat NEW Cat("Kitty", "Shorthaired")
CALL P.Speak()
CALL MyCat.Speak()

Encapsulation with getters/setters and validation

pseudocode §10.1 Run in Playground
CLASS Account
PRIVATE Balance : REAL
PUBLIC PROCEDURE NEW(Start : REAL)
Balance Start
ENDPROCEDURE
PUBLIC PROCEDURE Deposit(Amount : REAL)
IF Amount > 0 THEN
Balance Balance + Amount
ENDIF
ENDPROCEDURE
PUBLIC FUNCTION GetBalance() RETURNS REAL
RETURN Balance
ENDFUNCTION
ENDCLASS
DECLARE A : Account
A NEW Account(100.0)
CALL A.Deposit(50)
CALL A.Deposit(-20) // ignored by validation
OUTPUT A.GetBalance()
OUTPUT A.Balance // meant to fail: examiner-style PRIVATE error

Python equivalent with exception handling

python Run in Python Playground
class Account:
def __init__(self, start):
self.__balance = start
def deposit(self, amount):
if amount <= 0:
raise ValueError("Deposit must be positive")
self.__balance += amount
def get_balance(self):
return self.__balance
 
a = Account(100.0)
try:
a.deposit(-20)
except ValueError as e:
print("Rejected:", e)
finally:
print("Balance:", a.get_balance())

Random-access file of records (guide §9.2)

pseudocode §9.2 Run in Playground
TYPE Student
DECLARE Name : STRING
DECLARE Mark : INTEGER
ENDTYPE
DECLARE S : Student
DECLARE Pos : INTEGER
OPENFILE "marks.dat" FOR RANDOM
FOR Pos 1 TO 3
S.Name "P" & NUM_TO_STR(Pos)
S.Mark Pos * 25
SEEK "marks.dat", Pos
PUTRECORD "marks.dat", S
NEXT Pos
SEEK "marks.dat", 2
GETRECORD "marks.dat", S
OUTPUT "Record 2: ", S.Name, " ", S.Mark
CLOSEFILE "marks.dat"

Exception handling: TRY … EXCEPT … ENDTRY

pseudocode 9618 §20.3 Run in Playground
DECLARE Entry : STRING
DECLARE N : INTEGER
INPUT Entry
TRY
N STR_TO_NUM(Entry)
OUTPUT "Half of it is ", N / 2
EXCEPT
OUTPUT "That was not a number: ", ERRORMESSAGE()
ENDTRY
OUTPUT "The program did not crash"

💡 Not in the official pseudocode guide (§20.3 is examined in Python/VB/Java), but this is the accepted pseudocode form and it runs in the Playground. Python: try / except Exception as e / … ; the handler runs only if a statement in the TRY block raises an error.

Playground examples17runnable programs for this topic

  • Exception handling — TRY … EXCEPT … ENDTRY

    Validation stops bad data getting in; exception handling catches the runtime errors that slip through — division by zero, a failed conversion, an index out of range — so the program keeps running.

    A2PseudocodeValidation, testing & exceptions 9618 §20.3
    Run
  • Save records to a text file and load them back

    Write each record as one delimited line, then parse the lines back into an array of records.

    ASA2PseudocodeFile handling §4.1, §9.1
    Run
  • Random-access file — SEEK, PUTRECORD, GETRECORD

    Records are stored at addresses; SEEK moves the file pointer, then read or write the record there.

    A2PseudocodeFile handling §9.2
    Run
  • A class with a constructor, getter and setter

    The guide's PlayerClass: a PRIVATE attribute reached only through PUBLIC methods.

    A2PseudocodeObject-oriented programming §10.1
    Run
  • Inheritance — Animal and Dog

    Dog INHERITS Animal, calls SUPER.NEW, overrides Speak and adds its own methods.

    A2PseudocodeObject-oriented programming §10.2
    Run
  • Polymorphism — one Area() call, different shapes

    An array of Shape objects; each subclass overrides Area(), and the loop does not care which it is.

    A2PseudocodeObject-oriented programming §10.2
    Run
  • Encapsulation — a bank account that protects its balance

    Balance is PRIVATE; Deposit and Withdraw validate every change. Try uncommenting the last line.

    A2PseudocodeObject-oriented programming §10.1
    Run
  • Containment — a Car has an Engine

    One object stored inside another (has-a), as opposed to inheritance (is-a).

    A2PseudocodeObject-oriented programming §10.1–10.2
    Run
  • A Stack class

    The stack ADT wrapped in a class: the array and Top are PRIVATE, so only Push/Pop can touch them.

    A2PseudocodeObject-oriented programming §10.1 · 9618 §19.1
    Run
  • A2 Paper 4 — stock control with a Product class, files & exceptions

    A class with validation in its methods, an array of objects, the stock saved to a text file, then reloaded with TRY … EXCEPT protecting the program from a corrupt line.

    A2PseudocodeExam-style tasks §9.1, §10 · 9618 §20.3
    Run
  • Validation loop — range and type checks

    Keep asking until the input is a whole number between 1 and 100. try/except catches the ValueError from int().

    O LevelASPythonValidation, testing & exceptions §7.3 ↔ Python, A2 §20.3
    Run
  • try / except / finally — exception handling

    A2 §20.3: catch specific exceptions, use else and finally, raise your own. Compare with TRY … EXCEPT … ENDTRY.

    A2PythonValidation, testing & exceptions A2 §20.3 ↔ Python
    Run
  • Records in a file — CSV with the csv module

    A list of dictionaries written and read back as CSV, the way Paper 4 file-handling questions expect.

    A2PythonFile handling §9 ↔ Python
    Run
  • A class with private attributes, getters and setters

    Two underscores make an attribute private (name mangling). Access it through methods — encapsulation, the Paper 4 way.

    A2PythonObject-oriented programming §10.1 ↔ Python
    Run
  • Inheritance and polymorphism

    A subclass calls super().__init__ and overrides a method; the same call behaves differently for each object.

    A2PythonObject-oriented programming §10.2 ↔ Python
    Run
  • Containment — a class that holds other objects

    A Library object contains a list of Book objects (has-a), as opposed to inheritance (is-a).

    A2PythonObject-oriented programming §10 ↔ Python
    Run
  • 9618 Paper 4: class + file + exception

    The three Paper 4 ingredients in one: a class with private attributes, objects saved to a file and read back, with try/except on the file.

    A2PythonExam-style tasks 9618 §19–20
    Run

Assembler11programs to step through the CPU simulator

  • Immediate addressing

    The operand IS the value. LDM #25 puts 25 in ACC — no memory read happens in the execute stage.

    ASA2Addressing modes 9618 §4.2, §20.1
    Run
  • Direct addressing

    The operand is the address of the value. LDD 200 reads memory location 200. Watch MAR/MDR in the execute stage.

    ASA2Addressing modes 9618 §4.2, §20.1
    Run
  • Indirect addressing (LDI)

    The operand holds the address of the address. [200] = 300, so LDI 200 loads [300]. A pointer in assembly.

    ASA2Addressing modes 9618 §4.2, §20.1
    Run
  • Indexed addressing (LDX) — walking an array

    Address = operand + IX. With IX = 0, 1, 2… LDX 300 visits 300, 301, 302 — how a loop reads an array.

    ASA2Addressing modes 9618 §4.2, §20.1
    Run
  • Relative addressing (A2)

    The operand is an offset from the current instruction: JMP +2 skips the next instruction, LDD +3 reads the location three after this one. Position-independent code — §20.1.

    A2Addressing modes 9618 §20.1
    Run
  • All five addressing modes in one program

    Immediate, direct, indirect, indexed and relative, one after another — the summary table you should be able to reproduce in Paper 3.

    A2Addressing modes 9618 §4.2, §20.1
    Run
  • Sum an array — the working idiom

    Keep the loop counter in memory alongside IX: the counter is compared, IX does the indexing. Ends when COUNT = 0.

    ASA2Compare & jump 9618 §4.2
    Run
  • Linear search through memory

    Search for 30 in an array of 5 using LDX; output Y if found, N if not. Change TARGET to try both paths.

    ASA2Compare & jump 9618 §4.2
    Run
  • CMI — compare through a pointer

    CMI 200 compares ACC with the value at the address stored in 200 — indirect addressing for a compare.

    ASA2Compare & jump 9618 §4.2
    Run
  • Print a string stored in memory

    Characters live at consecutive addresses, ending with 0. LDX + INC IX walks them until the terminator.

    ASA2Input & output 9618 §4.2
    Run
  • Trace question: indirect and indexed together (A2)

    Paper 3 style: combine LDI, LDX and CMI and give the final contents of the registers.

    A2Exam-style traces 9618 §20.1
    Run

Declarative Lab33Prolog knowledge bases with sample queries

  • A family tree — facts and simple queries

    Facts state what is true. A query with a constant asks yes/no; a query with a variable (capital letter) asks Prolog to find every value that makes it true.

    A2Facts & queries 9618 §20.1
    Run
  • Capitals and continents

    Two-argument facts read as a relation. Ask in both directions — Prolog does not care which argument is the “input”.

    A2Facts & queries 9618 §20.1
    Run
  • Conjunction — two goals in one query

    A comma means AND. Prolog solves the first goal, then the second with the same variable values, backtracking if the second fails.

    A2Facts & queries 9618 §20.1
    Run
  • Rules — mother, father, grandparent

    A rule is true if its body is true. mother(M, C) :- parent(M, C), female(M). reads “M is the mother of C if M is a parent of C and M is female”.

    A2Rules 9618 §20.1
    Run
  • Siblings — and why X \= Y matters

    Without X \= Y, everyone is their own sibling. Run both queries and compare. Duplicated answers (one per shared parent) are normal Prolog behaviour.

    A2Rules 9618 §20.1
    Run
  • Several clauses for one predicate (OR)

    Two rules for can_drive: either condition makes it true. Prolog tries the first clause, then the second on backtracking.

    A2Rules 9618 §20.1
    Run
  • Watch backtracking happen

    Run the query and open the Resolution tab: Prolog picks a colour, tries to satisfy the second goal, fails, goes back (REDO) and tries the next one.

    A2Rules 9618 §20.1
    Run
  • ancestor/2 — the classic recursive rule

    Base case: a parent is an ancestor. Recursive case: a parent of an ancestor is an ancestor. Order of the clauses matters.

    A2Recursive rules 9618 §20.1
    Run
  • Routes through a network

    Is there a path from one station to another? Directed edges plus a recursive route/2. Try a start with no outgoing edge.

    A2Recursive rules 9618 §20.1
    Run
  • Left recursion — the infinite loop (this one is meant to fail)

    If the recursive call comes BEFORE the fact that makes progress, Prolog recurses forever. The Lab stops it with a depth error — reorder the goals in the second clause to fix it.

    A2Recursive rules 9618 §20.1
    Run
  • Lists — [Head | Tail]

    A list is a head and a tail. Unification splits it: [H|T] = [a, b, c] gives H = a, T = [b, c].

    A2Lists 9618 §20.1
    Run
  • member/2 and append/3

    Two built-ins you should be able to write yourself. member checks or generates; append joins, splits and even finds prefixes.

    A2Lists 9618 §20.1
    Run
  • Recursing over a list — length, sum, count

    Base case on [], recursive case on [H|T]. Note that the arithmetic comes AFTER the recursive call so N1 has a value.

    A2Lists 9618 §20.1
    Run
  • findall/3 — collect every answer in a list

    findall(Template, Goal, List) runs Goal for every solution and gathers the Template values. Then length/2 counts them.

    A2Lists 9618 §20.1
    Run
  • reverse, last, nth1, sum_list, max_list

    Handy list built-ins — and how reverse is written with an accumulator.

    A2Lists 9618 §20.1
    Run
  • is versus = — the most common A2 mistake

    = unifies structures; is evaluates. X = 2 + 3 leaves X as the term 2+3; X is 2 + 3 gives 5. The linter warns when a rule uses = with arithmetic.

    A2Arithmetic 9618 §20.1
    Run
  • Factorial and Fibonacci

    Recursion with arithmetic. The guard N > 0 stops the recursion running below zero.

    A2Arithmetic 9618 §20.1
    Run
  • Grades from marks — comparison operators

    =< and >= (not <= !), and a rule per band. The order of the guards keeps the bands from overlapping.

    A2Arithmetic 9618 §20.1
    Run
  • “Arguments are not sufficiently instantiated” (meant to fail)

    Arithmetic needs values. In the second rule the recursive call comes after N is used — N1 has no value yet, so 'is' throws. Compare with the working rule.

    A2Arithmetic 9618 §20.1
    Run
  • Negation as failure — \+

    \+ G succeeds if G cannot be proved. It never binds variables, so put \+ AFTER the goals that give its variables values.

    A2Negation & cut 9618 §20.1
    Run
  • The cut — commit to the first answer

    ! stops Prolog looking for other clauses of this predicate once it passes. max/3 and classify/2 use it as an if-then; remove the cut from classify and watch a mark get two grades.

    A2Negation & cut 9618 §20.1
    Run
  • If-then-else with -> ;

    ( Cond -> Then ; Else ) — the structured alternative to a cut.

    A2Negation & cut 9618 §20.1
    Run
  • write/1, nl/0 and fail-driven loops

    Print every solution with a failure-driven loop: the query fails at the end on purpose, having printed on the way.

    A2Negation & cut 9618 §20.1
    Run
  • bagof, setof and aggregate_all

    findall never fails and keeps duplicates; bagof groups by the free variable (one answer per group) and fails on nothing; setof sorts and removes duplicates. aggregate_all counts, sums or finds the max in one go.

    A2Lists 9618 §20.1
    Run
  • format/2 — neat output

    format(Format, Args): ~w writes a term, ~a an atom, ~d an integer, ~2f a float to 2 places, ~n a newline, ~t~20| pads to column 20. The fail-driven loop prints a table.

    A2Negation & cut 9618 §20.1
    Run
  • assert and retract — a counter that remembers

    The knowledge base can change while a query runs. retract removes the old fact, assert adds the new one — and the Lab keeps the change until you edit the code or press Restart session. Ask count(X) after a few increments.

    A2Negation & cut 9618 §20.1
    Run
  • catch and throw — handling errors

    A division by zero or an unbound variable raises an ISO error term; catch(Goal, Pattern, Recovery) matches it. safe_divide turns the error into an atom instead of stopping the query. The last query throws on purpose and is not caught — this one is meant to fail.

    A2Negation & cut 9618 §20.1
    Run
  • Atoms, strings and characters

    atom_length, atom_concat, sub_atom, upcase_atom, atom_chars, atom_codes, atom_number — and the double-quoted string type SWI-Prolog 7 introduced (a string never unifies with an atom).

    A2Lists 9618 §20.1
    Run
  • Why SWI-Prolog says false. after the last answer

    Prolog only knows there is nothing left when no choice point remains. With first-argument indexing, parent(sonia, X) ends with a full stop; grade(85, G) leaves the other clauses to try, so SWI (and this Lab) print G = a ; false. Examiners accept both, but knowing why is A2 understanding.

    A2Negation & cut 9618 §20.1
    Run
  • Exam: warehouse stock

    Numbered knowledge base as printed in Paper 3. Write the query to find items with fewer than 20 in stock, and the rule reorder(Item).

    A2Exam-style scenarios 9618 §20.1
    Run
  • Exam: teachers, rooms and clashes

    Facts about lessons; a rule that finds two lessons in the same room at the same time. Typical “write the rule” question.

    A2Exam-style scenarios 9618 §20.1
    Run
  • Exam: classifying animals

    Rules chained on rules — the expert-system style question. Ask what a given animal is and which animals are mammals.

    A2Exam-style scenarios 9618 §20.1, §18 AI
    Run
  • Exam: students, marks and averages

    findall, sum_list and length together — “write a rule average(Subject, Avg)”.

    A2Exam-style scenarios 9618 §20.1
    Run

OOP Designer9class diagrams with the skeleton code in four languages

  • BankAccount

    One class with a PRIVATE balance, a constructor, deposit/withdraw and a getter — the classic encapsulation question.

    A2A single class 9618 §20.1
    Open
  • Student with getters and setters

    Why attributes are PRIVATE and accessed through public methods.

    A2A single class 9618 §20.1
    Open
  • Shapes: inheritance and overriding

    Shape with Circle and Rectangle subclasses that override Area() — inheritance and polymorphism in one diagram.

    A2Inheritance 9618 §20.1
    Open
  • Vehicles

    Vehicle → Car and Lorry; the subclass constructors call SUPER.NEW.

    A2Inheritance 9618 §20.1
    Open
  • Employees and payroll (polymorphism)

    Employee with Pay() overridden by SalariedEmployee and HourlyEmployee — the same call, different calculation.

    A2Polymorphism 9618 §20.1
    Open
  • Car contains an Engine

    Containment: a Car has an Engine attribute — a has-a relationship, not is-a.

    A2Containment 9618 §20.1
    Open
  • Library: Book, Member, Loan

    Three classes where Loan contains a Book and a Member.

    A2Containment 9618 §20.1
    Open
  • Read: Animal, Dog, Cat

    Pseudocode with inheritance and an overridden Speak() — draw the class diagram from it.

    A2Read the code → draw the diagram 9618 §20.1
    Open
  • Read: a Stack class

    A class that wraps an array and TopPointer — the ADT as an object.

    A2Read the code → draw the diagram 9618 §20.1
    Open

Test yourself

Ready to check you know it?

Every round is a fresh random draw, weak cards come back until you get them right, and past-paper questions come with their mark schemes. Marks earn XP on your dashboard.

Enroll nowOnline classes