9618 CompSci Hub
๐Ÿ”Ž
โ— Ready
These notes are AI-assisted study material. Always cross-check against the official 9618 syllabus or your teacher before relying on them in an exam.

9618 Paper 1 โ€” AS Theory

Cambridge International A Level Computer Science 9618 (2026 Syllabus)
Paper 1 ยท 1h 30m ยท 75 marks Sections 1โ€“8 (theory) Multiple-choice + structured

1Data Representation

How numbers, characters, images and sound are stored as binary; conversion between bases; representation of negative numbers and fractions.

1.1 Number systems

Computers store all data as binary (base 2). Humans group binary into hexadecimal (base 16) because each hex digit maps to exactly 4 bits, making long binary strings readable.

DecimalBinaryHex
0โ€“90000โ€“10010โ€“9
101010A
151111F
2551111 1111FF
To convert binary โ†’ hex: group from the right in 4s, look each up. To convert hex โ†’ binary: replace each digit with its 4-bit pattern.

1.2 Binary Coded Decimal (BCD)

Each decimal digit (0โ€“9) is encoded in 4 bits independently. The number 47 in BCD is 0100 0111, not 00101111. Used where decimal accuracy matters (calculators, currency).

1.3 Negative numbers โ€” two's complement

The most significant bit becomes the sign bit with a negative place value. In 8-bit two's complement the range is โˆ’128 to +127.

Two's complement of N
flip all bits, then add 1
Example: โˆ’5 in 8 bits
+5 = 0000 0101 โ†’ flip โ†’ 1111 1010 โ†’ +1 โ†’ 1111 1011

1.4 Characters โ€” ASCII and Unicode

  • ASCII: 7 bits, 128 characters. Fine for English, no support for accents or non-Latin scripts.
  • Unicode (UTF-8 / UTF-16): variable length up to 4 bytes; covers every writing system; first 128 codepoints coincide with ASCII for backward compatibility.

1.5 Images and sound

Bitmap images store a colour value for every pixel.

Bitmap file size
size = width ร— height ร— colour depth (bits)

Vector images store drawing instructions (lines, curves, fills). Scale without loss but unsuitable for photographs.

Sound is captured by sampling amplitude at regular intervals.

Sound file size
size = sample rate ร— sample resolution ร— duration ร— channels
Higher sample rate โ†’ captures higher frequencies. Higher sample resolution โ†’ captures quieter sounds without quantisation noise.

2Communication

Networking, transmission modes, the Internet stack, and how packets find their way.

2.1 Transmission mode & direction

  • Serial: one bit at a time over one wire. Reliable over long distances. (USB, Ethernet)
  • Parallel: multiple bits simultaneously over multiple wires. Fast over short distances; suffers from skew over long ones.
  • Simplex: one direction only (TV broadcast).
  • Half-duplex: both directions, not simultaneously (walkie-talkie).
  • Full-duplex: both directions simultaneously (phone call).

2.2 Network topologies

TopologyProsCons
StarFailure of one node doesn't bring down the networkCentral switch is a single point of failure
BusCheap, simpleOne break breaks everything
MeshHighly resilient (multiple paths)Expensive, complex routing

2.3 The Internet, protocols, IPs

The Internet is a network of networks using the TCP/IP suite. Each connected device has an IP address; humans use domain names resolved by DNS.

  • IPv4: 32 bits, ~4.3 billion addresses (running out).
  • IPv6: 128 bits, effectively unlimited.
  • HTTP / HTTPS: web pages. HTTPS adds TLS encryption.
  • FTP: file transfer.
  • SMTP / POP3 / IMAP: email send / receive.

3Hardware

Logic gates, truth tables, Boolean expressions, and primary / secondary storage.

3.1 Logic gates

GateSymbol notationOutput is 1 whenโ€ฆ
ANDA ยท Bboth inputs are 1
ORA + Bat least one input is 1
NOTฤ€input is 0
NAND(A ยท B)'NOT both inputs are 1
NOR(A + B)'both inputs are 0
XORA โŠ• Binputs differ
A truth table with n inputs has 2n rows. Always write input combinations in binary-counting order.

3.2 Primary memory

  • RAM โ€” volatile, holds running programs and data. Two flavours: SRAM (cache, fast, expensive), DRAM (main memory, slower, denser).
  • ROM โ€” non-volatile, holds firmware (e.g. BIOS, bootloader).

3.3 Secondary & off-line storage

MediumHow it storesExamples
MagneticMagnetised regions on a spinning platterHDD, magnetic tape
OpticalPits and lands read by a laserCD, DVD, Blu-ray
Solid-stateFloating-gate transistorsSSD, USB drive, SD card

4Processor Fundamentals

CPU components, the fetch-execute cycle, interrupts, and assembly language.

4.1 CPU components

  • ALU โ€” Arithmetic Logic Unit. Performs arithmetic and bitwise operations.
  • CU โ€” Control Unit. Decodes instructions and orchestrates the other components.
  • Registers โ€” small ultra-fast storage. Key ones: PC, MAR, MDR, CIR, ACC, SR.
  • Buses โ€” Address bus (one-way), Data bus (two-way), Control bus (carries signals).

4.2 The fetchโ€“execute cycle

  1. Fetch: PC โ†’ MAR; memory[MAR] โ†’ MDR; MDR โ†’ CIR; PC = PC + 1.
  2. Decode: CU interprets the opcode in CIR.
  3. Execute: the operation is carried out; result may go to ACC or back to memory.

4.3 Interrupts

An interrupt is a signal that interrupts the current cycle: at the end of each fetch, the CPU checks the interrupt register. If set, it saves state (PC, registers) on the stack, jumps to the ISR (interrupt service routine), then restores state on return.

Examples: keypress, disk-finished, divide-by-zero, power-fail.

4.4 Assembly language

One mnemonic per machine instruction. Addressing modes you must know:

ModeOperand meansโ€ฆ
ImmediateThe actual value (e.g. LDM #5)
DirectThe address that holds the value (LDD 100)
IndirectThe address that holds the address (LDI 100)
IndexedAddress = base + index register (LDX 100)

5System Software

The operating system, utility programs, and the family of translators that turn human code into machine code.

5.1 Operating-system functions

  • Memory management (allocation, paging, virtual memory).
  • Process management (scheduling, multitasking).
  • File management (directories, permissions).
  • Device management (drivers, I/O).
  • Security & user accounts.
  • The user interface (GUI / CLI).

5.2 Utility programs

Disk defragmenter, file compression, anti-virus, backup. Strictly OS support but distinct from the kernel.

5.3 Translators

TypeBehaviourUse
CompilerTranslates the whole program once โ†’ executable.Production builds.
InterpreterTranslates and runs line-by-line.Scripting, interactive use.
AssemblerTranslates assembly โ†’ machine code.Low-level programming.

6Security, Privacy & Data Integrity

Threats to data, defences, and verification techniques.

6.1 Threats

  • Malware โ€” viruses, worms, trojans, ransomware, spyware.
  • Phishing & pharming โ€” social-engineering attacks.
  • Hacking โ€” unauthorised access for theft, vandalism, or sabotage.

6.2 Defences

  • Strong passwords, 2FA, biometrics.
  • Firewalls, anti-malware, encryption.
  • Regular patching and user training.

6.3 Data validation vs verification

ValidationVerification
Checks data is reasonable: range check, type check, length check, format check, presence check, check digit.Checks data has been copied accurately: double-entry, visual check, parity bit, checksum.

7Ethics & Ownership

The professional and legal landscape of computer science.
  • Copyright โ€” automatic legal protection of original works; covers expression, not ideas.
  • Patent โ€” granted for novel inventions; lasts ~20 years; must be applied for.
  • Open source โ€” source code released under a licence permitting reuse and modification (MIT, GPL, Apache).
  • Free software (FSF definition) โ€” the four freedoms: use, study, share, modify.
  • Professional ethics โ€” codes of conduct from BCS / ACM. Recurring themes: honesty, competence, privacy, public benefit.
Don't confuse "free as in beer" (no cost) with "free as in speech" (libre / open). Software can be either, both, or neither.

8Databases

Relational model, normalisation, and SQL basics.

8.1 The relational model

  • Entity โ€” a thing the database stores (Student, Book).
  • Attribute โ€” a property of an entity (Name, ISBN).
  • Primary key โ€” uniquely identifies a row.
  • Foreign key โ€” a primary key from another table, creating a relationship.

8.2 Normalisation

FormRule
1NFNo repeating groups; each cell holds a single atomic value.
2NF1NF, and every non-key attribute depends on the whole primary key.
3NF2NF, and no transitive dependencies (non-key attributes depend only on the key).

8.3 SQL โ€” DDL & DML basics

CREATE TABLE Student (
  StudentID INTEGER PRIMARY KEY,
  Name      VARCHAR(50) NOT NULL,
  ClassID   INTEGER,
  FOREIGN KEY (ClassID) REFERENCES Class(ClassID)
);

SELECT Name FROM Student WHERE ClassID = 1 ORDER BY Name;
INSERT INTO Student VALUES (42, 'Lin', 1);
UPDATE Student SET ClassID = 2 WHERE StudentID = 42;
DELETE FROM Student WHERE StudentID = 42;
These notes are AI-assisted study material. Always cross-check against the official 9618 syllabus or your teacher before relying on them in an exam.

9618 Paper 2 โ€” Fundamental Problem-solving & Programming

Cambridge International A Level Computer Science 9618 (2026 Syllabus)
Paper 2 ยท 2h ยท 75 marks Sections 9โ€“12 Pseudocode + chosen language

9Algorithm Design & Problem-solving

Decomposition, stepwise refinement, structure charts, pseudocode, flowcharts, trace tables.

9.1 The five basic constructs

  1. Assignment: x โ† 5 (pseudocode) / x = 5 (Python).
  2. Sequence: statements run in written order.
  3. Selection: IFโ€ฆTHENโ€ฆELSE / CASE.
  4. Iteration: FOR (count-controlled), WHILE (pre-test), REPEAT (post-test).
  5. Modularity: procedures and functions.

9.2 Pseudocode style (Cambridge)

// Variable declaration
DECLARE Score : INTEGER

// Selection
IF Score >= 50 THEN
   OUTPUT "Pass"
ELSE
   OUTPUT "Fail"
ENDIF

// Iteration
FOR i โ† 1 TO 10
   OUTPUT i
NEXT i

// Function
FUNCTION Square(n : INTEGER) RETURNS INTEGER
   RETURN n * n
ENDFUNCTION

9.3 Trace tables & dry-running

Track every variable's value after each line. Trace tables are how the exam tests whether you understand control flow.

Always include a column for the condition being tested (e.g. i < 10) โ€” that's where most mistakes happen.

9.4 Stepwise refinement

Decompose a problem into smaller modules; refine each module until it can be translated directly into pseudocode. Document with structure charts.

10Data Types & Structures

Built-in types, arrays (1D and 2D), records, and basic file handling.

10.1 Built-in data types

TypeHolds
INTEGERwhole numbers
REALnumbers with a decimal point
CHARa single character
STRINGa sequence of characters
BOOLEANTRUE / FALSE
DATEcalendar date

10.2 Arrays

// 1D โ€” 10 integers, indices 1..10
DECLARE Marks : ARRAY[1:10] OF INTEGER

// 2D โ€” 4 rows ร— 5 cols
DECLARE Grid : ARRAY[1:4, 1:5] OF INTEGER

FOR i โ† 1 TO 10
   Marks[i] โ† 0
NEXT i

10.3 Records (composite type)

TYPE TStudent
   DECLARE ID   : INTEGER
   DECLARE Name : STRING
   DECLARE Mark : REAL
ENDTYPE

DECLARE S : TStudent
S.Name โ† "Mei"

10.4 File handling

OPENFILE "marks.txt" FOR READ
WHILE NOT EOF("marks.txt") DO
   READFILE "marks.txt", Line
   OUTPUT Line
ENDWHILE
CLOSEFILE "marks.txt"
Three modes โ€” READ, WRITE (truncate), APPEND. Always pair OPENFILE with CLOSEFILE.

11Programming

From pseudocode to a real language. Cambridge accepts Python, Java, or VB.NET โ€” these notes use Python.

11.1 Python equivalents of pseudocode

# Selection
if score >= 50:
    print("Pass")
else:
    print("Fail")

# For loop โ€” Python range is exclusive at the end!
for i in range(1, 11):     # i = 1..10
    print(i)

# While loop
count = 0
while count < 10:
    count = count + 1

# Function
def square(n):
    return n * n

11.2 String handling

s = "Hello"
len(s)          # 5
s[0]            # 'H'
s.upper()       # 'HELLO'
s.lower()       # 'hello'
s + " world"    # 'Hello world'
int("42")       # 42
str(42)         # "42"

11.3 Arrays / lists

marks = [0] * 10                   # 10 zeros
marks[0] = 95
marks.append(72)
total = sum(marks)
avg   = total / len(marks)

11.4 Files

# Read
with open("marks.txt", "r") as f:
    for line in f:
        print(line.strip())

# Write
with open("out.txt", "w") as f:
    f.write("hello\n")

12Software Development

Program development lifecycle, testing, and maintaining code that works.

12.1 The development life cycle

  1. Analysis โ€” requirements gathering, feasibility.
  2. Design โ€” structure charts, pseudocode, data structures.
  3. Coding โ€” translation into the chosen language.
  4. Testing โ€” see 12.2.
  5. Maintenance โ€” fix bugs, add features after release.

12.2 Testing strategies

StrategyWhat it does
Black-boxTest by input/output only โ€” no view of internals.
White-boxUse knowledge of code paths; aim for branch / statement coverage.
AlphaInternal testing inside the developing organisation.
BetaPublic / limited-user testing before release.
AcceptanceBy the client to confirm the contract is met.

12.3 Test data choices

  • Normal โ€” typical valid input.
  • Boundary โ€” at the edges of accepted ranges (the bit examiners love).
  • Abnormal / invalid โ€” outside the range, wrong type, empty.

12.4 Maintainable code โ€” style rules

  • Meaningful identifier names (total_score, not x).
  • Consistent indentation.
  • Comments explaining why, not what.
  • Modular structure โ€” short procedures with one job each.
  • No magic numbers โ€” use named constants.
These notes are AI-assisted study material. Always cross-check against the official 9618 syllabus or your teacher before relying on them in an exam.

9618 Paper 3 โ€” Advanced Theory

Cambridge International A Level Computer Science 9618 (2026 Syllabus)
Paper 3 ยท 1h 30m ยท 75 marks Sections 13โ€“23 (theory)

13Data Representation

Numbers, characters, images, and sound โ€” how a computer stores them.

Number bases

Computers use binary (base 2). Humans often use hexadecimal (base 16) as a compact way to write binary because 4 binary digits = 1 hex digit.

BinaryDecimalHex
000000
101010A
111115F
11111111255FF

Two's complement (signed integers)

Two's complement: the standard way to represent negative integers. The most significant bit has a negative place value; everything else is positive.

For 8-bit two's complement, the MSB has value โˆ’128. So 10000000 = โˆ’128, 11111111 = โˆ’1, 01111111 = +127.

To negate a number:

  1. Invert all bits (one's complement)
  2. Add 1
Worked example
+5 in 8-bit: 00000101 โ†’ invert: 11111010 โ†’ add 1: 11111011 = โˆ’5

Binary Coded Decimal (BCD)

Each decimal digit (0โ€“9) is encoded as 4 bits. Used in calculators and electronic displays where precise decimal arithmetic matters.

ASCII vs Unicode

ASCIIUnicode
7 bits (128 chars)16+ bits (millions of chars)
English alphabet onlyAll world scripts
Small filesLarger files

14User-Defined Data Types

Building your own types: composite, non-composite, classes, pointers.

Non-composite types (enumerated, pointer)

Enumerated type: a user-defined list of named values with implicit ordering.
Example: TYPE TDayOfWeek = (Mon, Tue, Wed, Thu, Fri, Sat, Sun)
Pointer type: stores a memory address. TYPE TIntPtr = ^INTEGER declares a pointer to an integer.

Composite types (record, set, class)

Record

TYPE TStudent
   DECLARE Name : STRING
   DECLARE Age  : INTEGER
   DECLARE Mark : REAL
ENDTYPE

Records group different data types under one name. Each field has its own type. Access using dot notation: student.Name.

Set

A collection of unique values of the same type with set operations like union (โˆช), intersection (โˆฉ), difference (โˆ’).

Class

A blueprint for objects (covered in Topic 20.1 โ€” OOP).

When to use each

TypeUse when
EnumeratedFixed list of named options (months, suits)
PointerBuilding linked lists, trees, dynamic structures
RecordGrouping mixed fields about one thing
SetUnique items, mathematical set operations

15File Organisation & Access

Serial, sequential, random, index-sequential โ€” and hashing.

File organisation methods

MethodOrderBest for
SerialOrder of arrivalLogs, transaction files
SequentialSorted by keyPayroll, batch processing
Index-sequentialSorted + indexFast lookups + range queries
Random (direct)By hash addressFast direct lookups

Hashing

Hashing algorithm: a function that converts a key into a storage address. Example: address = key MOD table_size

Collisions

When two keys hash to the same address. Resolution methods:

  • Linear probing โ€” try next slot, then next, until empty.
  • Chaining โ€” store a linked list at each address.
  • Rehashing โ€” apply a second hash function.
A poor hash function creates many collisions and degrades to O(n) performance. Use a function that distributes keys evenly.

16Floating-Point Numbers

How real numbers are stored โ€” mantissa, exponent, normalisation.

Form

A floating-point number = mantissa ร— 2exponent. Both stored in two's complement.

Example layout (8-bit mantissa, 4-bit exponent)M = 0.5 ร— 23 = 4

Normalisation

Normalised form: the mantissa's first two bits are different (01โ€ฆ for positive, 10โ€ฆ for negative). This gives maximum precision.

Why normalise?

  • Unique representation for each value
  • Maximum precision in the available bits
  • Easier comparison

Errors

ErrorCause
OverflowNumber too large for the exponent
UnderflowNumber too small (very close to 0)
Rounding errorMantissa truncated
Loss of precisionSubtracting very similar numbers

17Communication & Networking

Protocols, TCP/IP, packet switching, circuit switching.

TCP/IP protocol stack (4 layers)

LayerRoleExamples
ApplicationUser-facing protocolsHTTP, FTP, SMTP, DNS
TransportEnd-to-end delivery, reliabilityTCP, UDP
InternetRouting, IP addressingIP, ICMP
Link (Network access)Physical transmissionEthernet, Wi-Fi

Packet switching

  • Data broken into small packets with headers
  • Each packet routed independently through the network
  • Reassembled at the destination
  • Resilient โ€” failed links cause re-routing, not failure

Circuit switching

Dedicated end-to-end path for the whole call (old telephone networks). Wastes bandwidth when idle, but no congestion once connected.

BitTorrent (peer-to-peer)

Files split into pieces shared between many peers. A tracker manages who has which piece. Reduces server load and is resilient.

18Hardware

CISC vs RISC, pipelining, parallel processing, virtual machines.

RISC vs CISC

RISCCISC
Few simple instructionsMany complex instructions
Each instruction one cycleVariable cycles
Fixed-length instructionsVariable-length
Hardwired controlMicrocoded
Lower power, mobile devicesDesktops, x86

Pipelining

The processor fetches the next instruction while still executing the current one โ€” like an assembly line. Stages typically: Fetch โ†’ Decode โ†’ Execute โ†’ Memory โ†’ Write-back.

Pipelining increases throughput, not the speed of any single instruction. A branch can stall (flush) the pipeline.

Parallel processing

  • SISD โ€” single instruction, single data (classical)
  • SIMD โ€” same instruction on many data items (graphics, vectors)
  • MIMD โ€” different instructions on different data (modern multi-core)
  • Massively parallel โ€” supercomputers, weather simulation

Virtual machines

Software that emulates a computer. Benefits: run multiple OSes on one host, isolated sandboxes, server consolidation. Drawbacks: slower than native, needs more RAM, single point of failure.

19System Software

OS functions, memory management, interrupts, scheduling, translation.

Operating system functions

  • Memory management
  • File management
  • Input/output management
  • Process / CPU scheduling
  • Security / access control
  • Provide user interface
  • Interrupt handling

Memory management

Paging

Physical memory divided into fixed page frames; programs divided into matching pages. A page table maps logical โ†’ physical pages.

Segmentation

Memory divided into variable-size segments matching logical units (code, stack, data). May cause external fragmentation.

Virtual memory

Uses disk as if it were RAM. Page fault = required page not in RAM โ†’ swap in from disk. Thrashing = excessive paging that slows the whole system.

Interrupts

Interrupt: a signal that pauses normal CPU execution so a higher-priority task can be handled.

Handling: save state on stack โ†’ run ISR (interrupt service routine) โ†’ restore state โ†’ resume. Sources: I/O, timer, hardware error, software exception.

Scheduling

AlgorithmIdea
FCFSFirst-come, first-served
SJFShortest job first
Round robinEach gets a time slice (quantum)
Multilevel feedbackMultiple queues, dynamic priority

Translation: compiler vs interpreter vs assembler

CompilerInterpreterAssembler
InputHigh-level sourceHigh-level sourceAssembly
OutputObject codeRuns line-by-lineMachine code
SpeedFast at runtimeSlow at runtimeFast
DebugHarderEasierHard

Compilation phases

  1. Lexical analysis โ€” break source into tokens; build symbol table
  2. Syntax analysis โ€” check tokens fit grammar; build parse tree
  3. Semantic analysis โ€” check meaning (types, declarations)
  4. Code generation โ€” produce object code
  5. Optimisation โ€” improve efficiency

20Security, Privacy & Data Integrity

Encryption, hashing, digital certificates, SSL/TLS, DRM.

Symmetric vs asymmetric encryption

SymmetricAsymmetric
Same key for encrypt/decryptPublic key + private key
FastSlower
Key distribution problemNo shared secret needed
AES, DESRSA

Digital signatures

  1. Sender hashes message โ†’ message digest
  2. Encrypts digest with their private key โ†’ signature
  3. Receiver decrypts with sender's public key โ†’ expected digest
  4. Receiver hashes message themselves and compares

SSL / TLS handshake

  1. Client sends "ClientHello" + supported ciphers
  2. Server responds with certificate + chosen cipher
  3. Client verifies certificate via Certificate Authority
  4. Both agree a symmetric session key (using asymmetric encryption)
  5. Rest of session uses fast symmetric encryption

Digital certificates

A document signed by a trusted Certificate Authority binding a public key to an identity. Contains: name, public key, validity period, CA's signature.

21Artificial Intelligence

Machine learning, neural networks, deep learning.

Categories

  • Narrow AI โ€” does one task well (chess, image recognition)
  • General AI โ€” human-level across tasks (research goal)
  • Strong AI โ€” exceeds human capability

Machine learning types

TypeDataExample
SupervisedLabelled inputs/outputsSpam detection, image classification
UnsupervisedUnlabelled โ€” find clustersCustomer segmentation
ReinforcementRewards from environmentGame-playing agents

Neural network

Layers of nodes (neurons). Each connection has a weight. Input ร— weight summed โ†’ activation function โ†’ output. Training adjusts weights to minimise error using back-propagation.

  • Input layer โ€” receives raw data
  • Hidden layers โ€” extract features
  • Output layer โ€” produces prediction

Deep learning = neural network with many hidden layers.

22Boolean Algebra & Logic Circuits

Truth tables, K-maps, flip-flops, half/full adders.

Boolean laws

LawForm
IdentityAยท1 = A, A+0 = A
NullAยท0 = 0, A+1 = 1
IdempotentAยทA = A, A+A = A
ComplementAยทAฬ… = 0, A+Aฬ… = 1
De Morgan 1(AยทB)ฬ… = Aฬ… + Bฬ…
De Morgan 2(A+B)ฬ… = Aฬ… ยท Bฬ…
DistributiveAยท(B+C) = AยทB + AยทC

Karnaugh maps (K-maps)

A grid arrangement of a truth table where adjacent cells differ by one variable (Gray code order). Group 1s in rectangles of size 1, 2, 4, 8โ€ฆ to simplify Boolean expressions.

Half adder

Two inputs (A, B), two outputs: Sum = AโŠ•B, Carry = AยทB.

Full adder

Three inputs (A, B, Cin), two outputs: Sum = AโŠ•BโŠ•Cin, Cout = (AยทB) + (Cinยท(AโŠ•B)).

Flip-flops

SR flip-flop

S=1, R=0 โ†’ Q=1 (set). S=0, R=1 โ†’ Q=0 (reset). S=R=0 โ†’ hold. S=R=1 โ†’ invalid.

JK flip-flop

Fixes SR's invalid state. J=K=1 โ†’ Q toggles. Clock-triggered.

Flip-flops are 1-bit memory cells โ€” combine many to build registers.

23BNF & RPN

Defining language grammars and evaluating expressions.

Backus-Naur Form (BNF)

BNF: a notation for defining context-free grammars. Uses ::= for "is defined as" and | for alternatives. Terminals are literal characters; non-terminals are wrapped in < >.
<digit> ::= 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9
<integer> ::= <digit> | <digit><integer>

The recursion in <integer> lets it match strings of any length.

Reverse Polish Notation (RPN)

Operators come after their operands. No brackets needed.

InfixRPN
3 + 43 4 +
(3 + 4) ร— 53 4 + 5 ร—
3 + 4 ร— 53 4 5 ร— +

Evaluating RPN with a stack

  1. Read left to right
  2. If number โ†’ push onto stack
  3. If operator โ†’ pop top two, apply, push result
  4. Final stack value = answer
Example: 3 4 + 5 ร—
Push 3 โ†’ [3]
Push 4 โ†’ [3,4]
+ โ†’ pop 4 and 3, push 7 โ†’ [7]
Push 5 โ†’ [7,5]
ร— โ†’ pop 5 and 7, push 35 โ†’ [35]
Answer: 35
These notes are AI-assisted study material. Always cross-check against the official 9618 syllabus or your teacher before relying on them in an exam.

9618 Paper 4 โ€” Practical Programming (Python)

Cambridge A Level Computer Science ยท Sections 19 + 20
Paper 4 ยท 2h 30m ยท 75 marks ยท 100% AO3 Computer-based, no internet

19.1aAlgorithms โ€” Searching

Linear search and binary search.

Linear search

Check each item until found โ€” works on any list, sorted or not.

def linear_search(arr, target):
    for i in range(len(arr)):
        if arr[i] == target:
            return i
    return -1

Complexity: O(n) worst case.

Binary search

Halve the search range each step. Requires sorted data.

def binary_search(arr, target):
    low, high = 0, len(arr) - 1
    while low <= high:
        mid = (low + high) // 2
        if arr[mid] == target:
            return mid
        elif arr[mid] < target:
            low = mid + 1
        else:
            high = mid - 1
    return -1

Complexity: O(log n).

If the array is not sorted, binary search gives wrong answers. State this requirement explicitly in exams.

19.1bAlgorithms โ€” Sorting

Bubble sort and insertion sort.

Bubble sort

Repeatedly compare adjacent items and swap if out of order. After each pass the largest unsorted element "bubbles" to the end.

def bubble_sort(arr):
    n = len(arr)
    for i in range(n - 1):
        for j in range(n - 1 - i):
            if arr[j] > arr[j+1]:
                arr[j], arr[j+1] = arr[j+1], arr[j]
    return arr

Complexity: O(nยฒ) worst, O(n) best (with early-exit flag).

Insertion sort

Build a sorted list one element at a time by inserting each new element in the right place.

def insertion_sort(arr):
    for i in range(1, len(arr)):
        key = arr[i]
        j = i - 1
        while j >= 0 and arr[j] > key:
            arr[j+1] = arr[j]
            j -= 1
        arr[j+1] = key
    return arr

Complexity: O(nยฒ) worst, O(n) best. Often faster than bubble in practice.

19.1cADTs โ€” Stack & Queue

LIFO and FIFO collections.

Stack (LIFO)

Operations: push, pop, peek, isEmpty.

class Stack:
    def __init__(self):
        self.__items = []
    def push(self, x): self.__items.append(x)
    def pop(self):
        if self.is_empty(): raise Exception("Stack underflow")
        return self.__items.pop()
    def peek(self): return self.__items[-1]
    def is_empty(self): return len(self.__items) == 0

Uses: function call stack, undo, expression evaluation, RPN.

Queue (FIFO)

class Queue:
    def __init__(self):
        self.__items = []
    def enqueue(self, x): self.__items.append(x)
    def dequeue(self):
        if self.is_empty(): raise Exception("Queue underflow")
        return self.__items.pop(0)
    def is_empty(self): return len(self.__items) == 0

Uses: print queue, breadth-first search, task scheduling, message buffers.

19.1dADTs โ€” Linked List & Binary Tree

Pointer-based dynamic structures.

Linked list

A chain of nodes. Each node holds data and a pointer to the next node. The head points to the first node; the last node points to None.

class Node:
    def __init__(self, data):
        self.data = data
        self.next = None

class LinkedList:
    def __init__(self):
        self.head = None
    def insert(self, data):
        n = Node(data); n.next = self.head; self.head = n
    def find(self, target):
        cur = self.head
        while cur:
            if cur.data == target: return True
            cur = cur.next
        return False

Binary search tree (BST)

Each node has up to two children. Rule: left child < parent < right child. In-order traversal visits values in sorted order.

class TreeNode:
    def __init__(self, data):
        self.data = data
        self.left = None
        self.right = None

19.1eDictionary & Graph

Dictionary

Key โ†’ value pairs. Average O(1) lookup. In Python use {}.

contacts = {"Alice": "1234", "Bob": "5678"}
print(contacts["Alice"])

Graph (knowledge only โ€” no code required)

A set of nodes (vertices) connected by edges. Edges can be directed/undirected and weighted/unweighted.

Uses: social networks, maps, computer networks, dependency graphs.

Implemented as an adjacency list (dictionary of neighbours) or adjacency matrix (2D array).

19.1fBig O Complexity

AlgorithmBestAverageWorst
Linear searchO(1)O(n)O(n)
Binary searchO(1)O(log n)O(log n)
Bubble sortO(n)O(nยฒ)O(nยฒ)
Insertion sortO(n)O(nยฒ)O(nยฒ)

Space complexity

How much extra memory the algorithm uses. Bubble sort = O(1) extra (in-place). Merge sort = O(n) extra.

19.2Recursion

A function that calls itself.

Essential features

  1. Base case โ€” when to stop
  2. Recursive call โ€” heading toward the base case
  3. Unwinding โ€” calls return back up the chain
def factorial(n):
    if n == 0:                  # base case
        return 1
    return n * factorial(n - 1) # recursive call

Stack frames

Each recursive call adds a new stack frame holding local variables and return address. Too many frames โ†’ stack overflow.

When recursion beats iteration

  • Tree / graph traversal
  • Divide-and-conquer (mergesort, quicksort)
  • Problems with naturally recursive definitions (factorial, Fibonacci, Towers of Hanoi)
Recursion uses more memory than iteration. Always identify the base case explicitly in comments.

20.1aOOP โ€” Classes & Objects

Key terms

TermMeaning
ClassBlueprint / template
Object (instance)Actual thing built from class
Attribute (property)Data stored in object
MethodFunction in a class
Constructor__init__ โ€” runs at object creation
class Student:
    def __init__(self, name, year):
        self.name = name
        self.year = year
    def greet(self):
        print(f"Hi, I'm {self.name}")

20.1bOOP โ€” Encapsulation & Inheritance

Encapsulation

Hide internal data using __ prefix (private). Provide controlled access via getters and setters (with validation).

class Account:
    def __init__(self, balance):
        self.__balance = balance
    def get_balance(self):
        return self.__balance
    def deposit(self, x):
        if x <= 0: raise Exception("Invalid")
        self.__balance += x

Inheritance ("is-a")

Child class reuses + extends parent.

class Animal:
    def __init__(self, name): self.name = name
    def speak(self): print("sound")

class Dog(Animal):
    def speak(self): print(f"{self.name} says Woof!")

20.1cOOP โ€” Polymorphism & Containment

Polymorphism ("many forms")

Same method name behaves differently on different classes. Achieved by method overriding.

Containment ("has-a") / Aggregation

An object holds another object as an attribute.

class Engine:
    def __init__(self, hp): self.hp = hp

class Car:
    def __init__(self, model, hp):
        self.model = model
        self.engine = Engine(hp)   # car HAS-A engine
Inheritance = "is-a" (Dog IS-A Animal). Containment = "has-a" (Car HAS-A Engine). Memorise the distinction for long-answer questions.

20.2File & Exception Handling

File modes

ModeMeaning
"r"Read (must exist)
"w"Write (creates/overwrites)
"a"Append (creates if needed)

File access types

  • Serial โ€” records in order of arrival
  • Sequential โ€” sorted by key, read in order
  • Random โ€” direct access by record number / hash

Reading and writing

with open("data.txt", "w") as f:
    f.write("Alice\n")
    f.write("Bob\n")

with open("data.txt", "r") as f:
    for line in f:
        print(line.strip())

Exception handling

try:
    x = int(input())
    print(100 / x)
except ValueError:
    print("Not a number")
except ZeroDivisionError:
    print("Can't divide by zero")
finally:
    print("Always runs")

Raise your own: raise Exception("message").

โ˜…Exam Strategy

Evidence document required

  • Full code listings (copy-paste from IDE)
  • Screenshots of program running each test case
  • Contents of any data files used

Test data โ€” three types

TypeExample (age 0-120)
Normal25
Boundary0, 120
Erroneous-1, 121, "abc"

Marks awarded for

  • Correctness of code
  • Meaningful identifier names
  • Comments and structure
  • Test evidence (screenshots)
  • Appropriate use of constructs (loops, functions, OOP)

Common pitfalls

  • Forgetting int(input()) for numeric input
  • Not using with open (file might not close)
  • No try/except around risky operations
  • Missing base case in recursion
  • Off-by-one errors in loops

9618 Computer Science ยท Tutor

AI can make mistakes. Always check important answers against the official 9618 syllabus or your teacher.