9618Computer Science

AS Level Computer Science, one topic at a time

Notes for every section of the Cambridge 9618 syllabus tested in Papers 1 and 2, with worked examples and exam-style questions. Write your answer in the lined box under each question, then open the mark scheme and tick off each point you made.

Paper 1: Theory Fundamentals

1 hour 30 minutes75 marks50% of AS

Topics 1 to 8. Short and structured written answers on theory: data, networks, hardware, the processor, system software, security, ethics and databases.

Paper 2: Problem-solving and Programming

2 hours75 marks50% of AS

Topics 9 to 12. Algorithms written in Cambridge-style pseudocode, data structures, program design and testing.

Topics

How to revise with these notes

  • Read, then close the page. After each section, try to explain it out loud or write the key terms from memory.
  • Answer before you look. Each question shows its marks. One mark usually means one distinct point, so a 4-mark question needs four separate ideas.
  • Use the command word. State wants a short fact. Describe wants what happens. Explain wants why or how. Compare wants both sides of each point.
  • Mark your progress. Use the button at the end of each topic. Your progress is saved in this browser only.
About the questions

The questions here are written in the style of real 9618 papers, covering the same skills and the kinds of answers examiners credit. They are not copies of official papers. For genuine past papers and mark schemes, use the Cambridge School Support Hub or ask your teacher.

Everything inside a computer, from numbers and text to photos and music, is stored as patterns of bits. This topic is about how those patterns are chosen, how big the files get, and how compression makes them smaller.

Number bases

A bit is a single binary digit (0 or 1). Eight bits make a byte, and four bits make a nibble. You need to convert fluently between three bases.

  • Denary (base 10): the numbers people use every day.
  • Binary (base 2): how the computer actually stores values.
  • Hexadecimal (base 16): digits 0 to 9 then A to F (A = 10 … F = 15). One hex digit represents exactly one nibble.
1286432168421Denary
10110101128+32+16+4+1 = 181

To convert 181 to hex, split the binary into nibbles: 1011 = 11 = B and 0101 = 5, so 181 = B5.

Why programmers use hex: it is shorter than binary, easier to read and copy, and less error-prone, yet it converts directly to binary. You see it in MAC addresses, HTML colour codes such as #FF8800, memory dumps and error codes.

Binary prefixes

Storage is measured in powers of 2, but the familiar prefixes (kilo, mega …) are powers of 10. The IEC binary prefixes remove the confusion.

Binary prefixValueDecimal prefixValue
kibi (Ki)210 = 1024kilo (k)103 = 1000
mebi (Mi)220 = 1 048 576mega (M)106
gibi (Gi)230giga (G)109
tebi (Ti)240tera (T)1012
Exam tipTo get kibibytes divide bytes by 1024; for mebibytes divide by 1024 twice. If a question asks for KiB or MiB, the examiner expects 1024, not 1000.

Negative numbers: one's and two's complement

In two's complement the most significant bit (MSB) has a negative place value. In 8 bits the column values are −128, 64, 32, 16, 8, 4, 2, 1, so the range is −128 to +127.

To write a negative number: write the positive version in binary, flip every bit (that gives the one's complement), then add 1.

+750100 1011
Flip the bits (one's complement)1011 0100
Add 1 (two's complement of −75)1011 0101
Check: −128 + 32 + 16 + 4 + 1= −75 ✓

Binary arithmetic and overflow

Binary addition follows four rules: 0+0 = 0, 0+1 = 1, 1+1 = 0 carry 1, and 1+1+1 = 1 carry 1. To subtract, add the two's complement of the second number and ignore any carry out of the MSB.

  45 − 20  =  45 + (−20)
    0010 1101      (+45)
  + 1110 1100      (−20)
  -----------
  1 0001 1001      discard the carry out  →  0001 1001 = 25 ✓

Overflow happens when a result is too large for the number of bits available. In two's complement you can spot it when two positives give a negative result, or two negatives give a positive one.

    0101 1010      (+90)
  + 0011 1100      (+60)
  -----------
    1001 0110      the MSB is 1, so this reads as −106, not +150. Overflow.

Binary-coded decimal (BCD)

In BCD each denary digit is stored as its own 4-bit nibble. For example, 59 is 0101 1001, not the pure binary 0011 1011. Nibbles 1010 to 1111 are never used.

  • Uses: digital clocks, calculators and electronic displays, where each digit is shown separately; and financial values, where BCD avoids the rounding errors of binary fractions.
  • Drawback: it wastes space compared with pure binary, and arithmetic is more complex.

Character sets

Character set
The full list of characters a computer recognises, each with a unique binary code.
ASCII
Uses 7 bits, so 128 characters: English letters, digits, punctuation and control codes. Extended ASCII uses 8 bits for 256 characters.
Unicode
Uses up to 4 bytes per character, so it can represent every writing system (Urdu, Arabic, Chinese …) plus symbols and emoji. Its first 128 codes match ASCII.

Codes run in order: 'A' = 65, 'B' = 66 …; 'a' = 97; '0' = 48. This is why programs can sort text and convert case with arithmetic, for example CHR(ASC('a') − 32) gives 'A'. Unicode's drawback is that each character can take more storage than in ASCII.

Bitmap images

Pixel
The smallest addressable element (picture element) of an image.
Colour depth
The number of bits used to store the colour of one pixel. n bits give 2n possible colours.
Image resolution
The number of pixels in the image, written as width × height.
Screen resolution
The number of pixels the screen can display, width × height.
File header
Data at the start of the file describing the image: file type, width, height, colour depth, compression used.

File size (bits) = width × height × colour depth

Increasing the resolution or colour depth improves quality but increases the file size.

Vector graphics

A vector graphic stores a drawing list: a set of drawing objects (lines, circles, rectangles, curves) and the properties of each one, such as its coordinates, radius, line colour, line thickness and fill colour. The image is redrawn from these instructions whenever it is displayed.

BitmapVector
StoresThe colour of every pixelObjects and their properties
ScalingBecomes pixelated when enlargedScales to any size with no loss of quality
File sizeDepends on resolution and colour depthUsually smaller for simple images
Best forPhotographs and detailed imagesLogos, diagrams, maps, fonts

Sound

Sound is an analogue wave. To store it digitally the amplitude is measured (sampled) at regular intervals by an analogue-to-digital converter.

Sampling rate
The number of samples taken per second, measured in hertz (Hz).
Sampling resolution
The number of bits used to store each sample (also called bit depth).

File size (bits) = sampling rate × sampling resolution × length in seconds (× number of channels)

A higher sampling rate or resolution gives a closer match to the original sound, but a larger file.

Compression

Compression reduces file size so files take less storage, transfer faster and use less bandwidth.

LosslessLossy
The original file can be reconstructed exactly.Some data is permanently removed, so the original cannot be restored.
Needed for text, program code and spreadsheets, where every bit matters.Fine for photos, video and music, where people won't notice small losses.
Examples: run-length encoding (RLE), PNG, ZIP.Examples: JPEG, MP3, MP4.

Run-length encoding (RLE)

RLE replaces a run of identical values with one copy of the value and a count. A row of pixels W W W W B B W W W becomes 4W 2B 3W; the text AAAAABBBCCCCCCCC becomes 5A 3B 8C. RLE works well on images with large blocks of colour but can make files bigger when there are few repeats, such as in photographs.

How lossy methods save space

  • Images: reduce the resolution or colour depth, or (as JPEG does) remove fine detail and colour differences the human eye barely notices.
  • Sound: perceptual coding removes frequencies outside human hearing and quiet sounds masked by louder ones. Lowering the sampling rate or resolution also helps.

Exam-style questions

Written in the style of Paper 1. Answer without a calculator, as in the exam.

1Paper 1 style
(a)
Convert the 8-bit two's complement binary number 1011 0110 into denary.
[1]
(b)
Convert the denary number 213 into hexadecimal.
[1]
(c)
Write the denary number 87 in Binary Coded Decimal (BCD).
[1]
(d)
Give one practical use of BCD.
[1]
Show mark scheme
  • (a) −74  (−128 + 32 + 16 + 4 + 2)
  • (b) D5  (1101 = D, 0101 = 5)
  • (c) 1000 0111
  • (d) Any one: digital clock display; calculator display; storing currency or other financial values exactly.
2Paper 1 style
Explain the difference between a kibibyte and a kilobyte.
[2]
Show mark scheme
  • A kibibyte is 1024 (210) bytes.
  • A kilobyte is 1000 (103) bytes, so the kibibyte is a binary (base 2) prefix and the kilobyte is a decimal (base 10) prefix.
3Paper 1 style

A bitmap image is 800 pixels wide and 600 pixels high, with a colour depth of 16 bits.

(a)
Calculate the file size of the image in kibibytes (KiB). Ignore the file header. Show your working.
[3]
(b)
The colour depth is reduced to 8 bits. Describe the effect this has on the image and on the file.
[2]
Show mark scheme
(a)
  • 800 × 600 = 480 000 pixels
  • × 16 bits = 7 680 000 bits, or × 2 bytes = 960 000 bytes
  • 960 000 ÷ 1024 = 937.5 KiB
(b)
  • Fewer colours can be shown (256 instead of 65 536), so image quality may be reduced, for example visible banding.
  • The file size halves (to about 468.75 KiB).
4Paper 1 style

A one-minute mono sound clip is recorded with a sampling rate of 32 000 Hz and a sampling resolution of 16 bits.

(a)
Calculate the file size in mebibytes (MiB), to two decimal places. Show your working.
[3]
(b)
Explain the effect of increasing the sampling resolution.
[2]
Show mark scheme
(a)
  • 32 000 × 16 × 60 = 30 720 000 bits
  • ÷ 8 = 3 840 000 bytes
  • ÷ 1024 ÷ 1024 = 3.66 MiB
(b)
  • More bits per sample means more possible amplitude values, so each sample is more accurate and the recording is closer to the original sound.
  • The file size increases.
5Paper 1 style
(a)
Explain how run-length encoding (RLE) compresses a bitmap image.
[3]
(b)
Explain why RLE may not reduce the file size of a photograph.
[1]
Show mark scheme
  • (a) RLE is a lossless method that finds runs of consecutive pixels with the same colour.
  • (a) Each run is stored as two values: the number of pixels in the run and the colour code.
  • (a) For example, 12 consecutive red pixels are stored once with a count of 12 instead of 12 times.
  • (b) Photographs contain few runs of identical pixels, so storing a count for each colour can make the file the same size or larger.
6Paper 1 style
Add the two 8-bit two's complement numbers 0110 0100 and 0010 1000. Show your working and explain the result.
[3]
Show mark scheme
  • Result: 1000 1100
  • The two numbers are positive (+100 and +40) but the result has an MSB of 1, so it reads as −116.
  • The true answer, 140, is larger than the maximum of +127, so overflow has occurred.

A network is two or more devices connected so they can share data and resources. This topic covers how networks are organised, the hardware that connects them, how the internet finds a device, and how media is streamed.

LANs and WANs

Local Area Network (LAN)Wide Area Network (WAN)
AreaA small geographical area, such as one building or siteA large geographical area, such as a country or the world
OwnershipUsually owned by one organisationUses infrastructure owned by third parties, such as telecoms companies
HardwareSwitches, cables, WAPsRouters, modems, leased lines, satellites
ExampleA school networkThe internet; a bank linking its branches

Reasons for networking: share files, printers and an internet connection; central backups; communication such as email; software can be installed and updated centrally.

Client-server and peer-to-peer

Client-serverPeer-to-peer (P2P)
Central servers provide services (files, email, web pages, printing) to clients that request them.All computers have equal status and share resources directly with each other.
Central control of security, backups and user accounts.Each user manages their own security and backups.
Costs more: a server and a network manager are needed.Cheap and easy to set up.
If the server fails, clients lose its services.No single point of failure, but performance falls when a peer is busy.
Used by schools, companies, websites.Used for small home networks and file sharing such as BitTorrent.

Thin and thick clients

A thin client depends heavily on the server: it needs a constant connection and does little processing itself, so it is cheap and easy to manage. A thick (fat) client can process and store data locally and still work when the connection drops, but costs more and is harder to keep updated and secure.

Network topologies

Bus
One shared backbone cable with a terminator at each end
Switch Star
Every device has its own cable to a central switch
Mesh
Devices link to many others, so there are several routes
A hybrid topology combines two or more of these, for example several star networks joined by a bus backbone.
TopologyBenefitsDrawbacks
BusCheap, uses the least cable, easy to add devicesIf the backbone fails the whole network fails; collisions increase and performance drops as traffic grows; less secure, since every device sees all the data
StarOne cable failing affects only one device; the switch sends data only to its destination, so it is fast and more secure; easy to find faultsNeeds more cable; if the central switch fails the whole network fails
MeshVery reliable: data can be rerouted if a link fails; handles high trafficExpensive and complex to install and manage
HybridFlexible; can join networks of different topologies and grow easilyComplex to design; can need expensive hardware

Cloud computing

Cloud computing means using storage, software or processing power provided over the internet by remote servers. A public cloud is shared infrastructure run by a provider and sold to anyone. A private cloud is dedicated to one organisation, either on its own servers or hosted for it.

  • Benefits: access from anywhere on any device; no need to buy and maintain your own hardware; storage scales up or down as needed; the provider handles backups and security patches.
  • Drawbacks: needs a reliable internet connection; data security and privacy depend on the provider; ongoing subscription costs; the provider could go out of business or suffer an outage.

Wired and wireless transmission

MediumNotes
Copper cable (twisted pair, coaxial)Cheap and easy to install. Lower bandwidth than fibre; signal weakens over distance and suffers interference.
Fibre-optic cableSends light pulses. Very high bandwidth, long distances without repeaters, no electromagnetic interference. More expensive and harder to install.
Radio waves (Wi-Fi, Bluetooth)No cables, so devices are mobile. Shorter range; signal is weakened by walls; easier to intercept, so it needs encryption.
MicrowavesLine-of-sight links between towers. Higher frequency, higher bandwidth than radio.
SatellitesCover remote areas and very large distances. There is a noticeable delay (latency) because of the distance the signal travels.

Network hardware

Network Interface Card (NIC)
Connects a device to a wired network. It has a unique MAC address.
Wireless NIC (WNIC)
Lets a device connect to a wireless network.
Wireless Access Point (WAP)
Lets wireless devices join a wired network.
Switch
Connects devices in a LAN. It reads the destination MAC address and sends each frame only to the device it is for.
Router
Connects different networks (for example a LAN to the internet) and forwards packets towards their destination using IP addresses.
Bridge
Joins two LAN segments that use the same protocol so they act as one network.
Repeater
Regenerates (boosts) a signal so it can travel further along a cable.
Server
A computer that provides a service to clients, such as a file, web, print or mail server.
Modem
Converts digital signals to analogue for transmission over telephone lines, and back again.

The internet is carried over a mix of infrastructure: the public switched telephone network (PSTN), dedicated (leased) lines, and the cell phone network.

Ethernet and CSMA/CD

Ethernet is the most common protocol for wired LANs. Data is sent in frames containing the source and destination MAC addresses. On a shared medium, two devices may transmit at once and cause a collision. CSMA/CD (Carrier Sense Multiple Access with Collision Detection) deals with this:

  1. A device that wants to send listens to check whether the channel is idle (carrier sense).
  2. If it is idle, the device starts transmitting; otherwise it waits.
  3. While transmitting, the device keeps listening for a collision.
  4. If it detects a collision, it stops and sends a jam signal so every device knows.
  5. Each device waits a random time (back-off) before trying again, so they are unlikely to collide again.

The internet and the World Wide Web

The internet is the global network of interconnected networks: the hardware and infrastructure. The World Wide Web is a collection of linked web pages and resources that are accessed using the internet, through a browser and HTTP(S). Email and online gaming also use the internet but are not part of the web.

IP addressing

IPv4IPv6
Size32 bits128 bits
FormatFour denary numbers 0 to 255 separated by dots, such as 192.168.0.12Eight groups of four hex digits separated by colons, such as 2001:0db8:0000:0000:0000:ff00:0042:8329
ShorteningNoneLeading zeros in a group can be dropped, and one run of all-zero groups can be replaced by ::, giving 2001:db8::ff00:42:8329

Why IPv6: IPv4 allows only about 4.3 billion addresses, which have run out as more devices connect. IPv6 gives 2128 addresses, and it removes the need for workarounds such as address translation.

Public IP address
Unique across the whole internet, assigned by an ISP. It can be reached from the internet.
Private IP address
Used only inside a LAN (for example ranges starting 192.168. or 10.). It can be reused on other LANs and cannot be reached directly from the internet; the router translates it.
Static IP address
Stays the same every time the device connects. Used for servers that must always be found at the same address.
Dynamic IP address
Allocated each time the device connects (by DHCP) and may change. It makes efficient use of a limited pool of addresses.
Subnetting
Dividing a network into smaller sub-networks. The IP address is split into a network ID and a host ID. Subnetting improves security and management and reduces traffic, because data stays inside its subnet.

URLs and the Domain Name Service

A URL (Uniform Resource Locator) is the text address of a resource, for example https://www.example.com/notes/page1.html: protocol, domain name, then path. People remember names; computers need IP addresses. The DNS converts one to the other:

  1. The user types a URL into the browser.
  2. The browser sends the domain name to a DNS server (the browser and operating system check their own caches first).
  3. The DNS server looks up the domain name in its database. If it doesn't have the entry, it passes the request to another DNS server higher in the hierarchy.
  4. The IP address is returned to the browser, which may cache it.
  5. The browser sends its request to the web server at that IP address.

Streaming

Bit streaming sends media as a continuous stream of bits, so playback begins before the whole file has downloaded. Real-time streaming sends a live event as it happens; on-demand streaming sends stored media whenever a user chooses to watch.

The receiver stores incoming data in a buffer. The media player reads from the buffer at a steady rate while new data keeps arriving, so short drops in network speed don't interrupt playback. The higher the bit rate (bits per second) needed, the faster the connection must be: higher-quality video needs more bandwidth.

Exam-style questions

1Paper 1 style
A small company is deciding between a client-server network and a peer-to-peer network. Compare the two models.
[4]
Show mark scheme

One mark per valid comparison point, max 4. Each point must refer to both models.

  • Client-server has a central server that provides resources, whereas in P2P each computer has equal status and shares its own resources.
  • Client-server allows central management of security, user accounts and backups; in P2P each user must manage their own.
  • Client-server is more expensive (server hardware, a network manager); P2P is cheaper and simpler to set up.
  • In client-server the server is a single point of failure; in P2P there is no central point of failure.
  • Client-server performance depends on the server and suits many users; P2P can slow down when a peer is being used heavily.
2Paper 1 style
Describe how CSMA/CD is used to manage the transmission of data on an Ethernet network.
[4]
Show mark scheme
  • Before transmitting, a device checks (listens) whether the channel is busy.
  • If the channel is idle the device transmits; if busy it waits.
  • While transmitting, the device monitors the channel for a collision.
  • If a collision is detected, transmission stops and a jam signal is sent.
  • Each device waits a random time before trying to retransmit.

Max 4.

3Paper 1 style
(a)
State whether each address is a valid IPv4 address, a valid IPv6 address, or invalid.
192.168.1.256   10.0.0.1   2001:db8::8a2e:370:7334   FE80::1G
[4]
(b)
Explain why IPv6 was introduced.
[2]
(c)
Explain the difference between a public IP address and a private IP address.
[2]
Show mark scheme
  • (a) 192.168.1.256 invalid: each IPv4 number must be 0 to 255.
  • (a) 10.0.0.1 valid IPv4.
  • (a) 2001:db8::8a2e:370:7334 valid IPv6 (zero compression used).
  • (a) FE80::1G invalid: G is not a hexadecimal digit.
  • (b) The number of IPv4 addresses (32 bits, about 4.3 billion) has run out because so many devices connect to the internet.
  • (b) IPv6 uses 128 bits, giving vastly more unique addresses.
  • (c) A public address is unique on the internet and can be reached from outside the network.
  • (c) A private address is used only within a LAN, can be repeated on other LANs, and is not directly reachable from the internet.
4Paper 1 style
A user types a URL into a web browser. Describe how the Domain Name Service (DNS) is used to find the IP address of the web server.
[4]
Show mark scheme
  • The browser sends the domain name part of the URL to a DNS server.
  • The DNS server searches its database for the matching IP address.
  • If it isn't found, the request is passed on to another DNS server at a higher level.
  • When found, the IP address is returned to the browser (and may be cached).
  • The browser uses the IP address to send a request to the web server.

Max 4.

5Paper 1 style
A video streaming service uses bit streaming. Explain why the media player uses a buffer.
[3]
Show mark scheme
  • Data arrives over the network at a rate that varies.
  • The buffer stores data that has arrived but not yet been played.
  • The player reads from the buffer at a constant rate, so playback continues smoothly even if the connection briefly slows.
  • Playback can start before the whole file has been downloaded.

Max 3.

A computer needs devices to take data in, put results out, and store things for the short and long term. The second half of this topic goes down to the logic gates every processor is built from.

Why a computer needs each type of hardware

Input devices
Let data and instructions enter the computer (keyboard, microphone, touchscreen, sensors).
Output devices
Present results to the user or another system (screen, printer, speakers, actuators).
Primary memory
RAM and ROM, directly accessible by the CPU. RAM holds the programs and data currently in use.
Secondary storage
Non-volatile storage that keeps programs and files when the power is off (hard disk, SSD, optical disc). Removable storage such as USB flash drives lets data be moved between computers or kept as a backup.

Embedded systems

An embedded system is a small computer built into a larger device to carry out one dedicated function, such as the controller in a washing machine, microwave, car engine management unit or smart thermostat. It usually has a microcontroller with its program stored in ROM or flash memory.

  • Benefits: small, cheap to mass-produce, low power, reliable, and starts instantly.
  • Drawbacks: hard or impossible to upgrade, and difficult to repair. If connected to the internet, it can be a security risk.

How the main devices work

Laser printer

  1. The printing drum is given an electrostatic charge.
  2. A laser beam scans across the rotating drum, removing the charge where the image should not be, so a charged pattern of the page is left.
  3. Charged toner is attracted to the charged areas of the drum.
  4. The paper is given a charge and passes over the drum, so the toner transfers onto the paper.
  5. A fuser (heated rollers) melts the toner so it is fixed permanently to the paper.
  6. A discharge lamp removes the remaining charge from the drum ready for the next page.

3D printer

A 3D design (from CAD software) is sliced into thin horizontal layers. The printer builds the object one layer at a time, usually by extruding melted plastic through a heated nozzle that moves in the x and y directions, while the platform moves down. Other types use resin cured by a UV laser, or powder fused by a laser.

Microphone and speaker

In a microphone, sound waves make a diaphragm vibrate. The vibration moves a coil in a magnetic field (or changes capacitance), producing a varying electrical signal. This analogue signal is converted to digital by an ADC.

In a speaker, a DAC converts digital data to an analogue electrical signal. The current flows through a coil attached to a cone; the changing current makes the coil move in and out within a permanent magnet's field, so the cone vibrates and creates sound waves.

Magnetic hard disk

Data is stored on spinning platters coated with magnetic material. Each surface is divided into concentric tracks, which are split into sectors. A read/write head on an actuator arm moves across the platter. To write, the head magnetises tiny areas in one of two directions to represent 1 or 0; to read, it detects the direction of magnetisation.

Solid-state (flash) memory

An SSD stores data in NAND flash memory made of transistors arranged in a grid. Each cell traps electrons in a floating gate (insulated by an oxide layer) to represent a bit, so the data stays when power is removed. There are no moving parts, which makes SSDs faster, quieter, more robust and lower power than hard disks, though cells can wear out after many writes.

Optical disc reader and writer

A laser shines onto the surface of a spinning disc, following a single spiral track. The surface has pits and lands that reflect light differently; a sensor detects the reflected light and the changes are read as binary. To write, a higher-power laser burns marks into a dye layer. Blu-ray uses a shorter-wavelength (blue) laser, so data can be packed more densely than on CD or DVD.

Touchscreen

A capacitive screen has a conductive layer carrying an electrostatic field. A finger (which conducts) changes the capacitance at the point touched, and the controller calculates its position from sensors at the corners. It supports multi-touch but doesn't work with ordinary gloves. A resistive screen has two flexible conductive layers separated by a gap; pressing joins them at that point and completes a circuit. It works with any stylus but is less clear and less responsive.

Virtual reality headset

The headset has two small screens (one per eye) showing slightly different images, so the user sees in stereoscopic 3D. Lenses focus the image. Sensors such as gyroscopes and accelerometers track head movement, and the image is updated to match so the user feels inside the scene. Headphones give spatial sound, and some headsets track eye movement too.

Buffers

A buffer is a temporary area of memory that holds data being transferred between two devices or processes that work at different speeds. For example, a printer buffer receives a whole document quickly from the CPU, so the CPU can carry on with other tasks while the slower printer prints from the buffer. Video streaming uses a buffer in the same way.

RAM and ROM

RAM (Random Access Memory)ROM (Read Only Memory)
Volatile: contents are lost when the power is offNon-volatile: contents are kept without power
Can be read from and written toCan only be read in normal use
Holds the operating system, programs and data currently in useHolds the start-up instructions (bootstrap, BIOS) and firmware
Usually larger (gigabytes)Usually small

SRAM and DRAM

DRAM (Dynamic RAM)SRAM (Static RAM)
Each bit is stored by a transistor and capacitorEach bit is stored by a flip-flop
Capacitors leak charge, so it must be refreshed constantlyDoesn't need refreshing while powered
Slower accessFaster access
Cheaper per bit, higher density (more GB per chip)More expensive, lower density
Used for main memoryUsed for cache memory in the CPU

Types of ROM

PROM
Programmable ROM: blank when made, can be programmed once by the user (fuses are burnt) and then can't be changed.
EPROM
Erasable PROM: can be erased by exposing the chip to ultraviolet light through a window, then reprogrammed. The chip must be removed to be erased, and the whole chip is erased at once.
EEPROM
Electrically Erasable PROM: can be erased and rewritten electrically while still in the device, byte by byte. Flash memory is a type of EEPROM. Used for firmware that may need updating.

Monitoring and control systems

A monitoring system uses sensors to read the environment and alerts or records, but doesn't change anything (for example a hospital heart monitor or pollution monitor). A control system also uses actuators (motors, valves, heaters, pumps) to change the environment.

Most control systems use feedback: the output affects the next input. For example, a greenhouse:

  1. A temperature sensor sends a reading, converted to digital by an ADC.
  2. The microprocessor compares the reading with the stored target value.
  3. If it is too cold, a signal is sent (through a DAC if needed) to an actuator to turn on the heater; if too hot, to open a window.
  4. The process repeats continuously, so the new temperature is read and the system keeps adjusting.
Exam tipA sensor never "decides" anything. Say that the processor compares the sensor reading with a stored value, then sends a signal to an actuator.

Logic gates

A logic gate takes one or more binary inputs and produces one binary output. Learn the symbol and truth table for each of these six.

NOT
X = NOT A
Output is the opposite of the input
AND
X = A AND B
1 only if both inputs are 1
OR
X = A OR B
1 if either input (or both) is 1
NAND
X = A NAND B
NOT AND: 0 only if both are 1
NOR
X = A NOR B
NOT OR: 1 only if both are 0
XOR
X = A XOR B
1 if the inputs are different
ABANDORNANDNORXOR
0000110
0101101
1001101
1111000

Logic circuits and expressions

Gates join to make circuits. You must be able to move between four forms: a problem statement, a logic expression, a circuit diagram and a truth table. Here is the circuit for X = (A AND B) OR (NOT C):

ABC X
Work from the inputs towards the output. A truth table with 3 inputs has 23 = 8 rows; list the inputs in binary counting order (000, 001 … 111) so you don't miss a row.
Exam tipWhen building a truth table by hand, add a working column for each intermediate gate output (such as A AND B, then NOT C). It earns method marks and catches mistakes.

Exam-style questions

1Paper 1 style
Describe two differences between Static RAM (SRAM) and Dynamic RAM (DRAM), and state where each is typically used.
[4]
Show mark scheme
  • DRAM must be refreshed regularly because its capacitors leak charge; SRAM does not need refreshing.
  • SRAM has faster access times than DRAM.
  • DRAM is cheaper per bit and has higher storage density than SRAM.
  • DRAM uses a capacitor and transistor per bit; SRAM uses flip-flops.
  • SRAM is used for cache memory; DRAM is used for main memory.

Max 3 for differences, 1 for both uses. Max 4.

2Paper 1 style
Describe how a laser printer prints a page.
[5]
Show mark scheme
  • The drum is given a (positive/negative) electrostatic charge.
  • A laser scans the drum, removing charge to leave an electrostatic image of the page.
  • The drum is coated with charged toner, which sticks only to the charged areas.
  • Charged paper passes over the drum and the toner transfers to the paper.
  • The fuser heats the paper so the toner melts and fixes to it.
  • The charge is removed from the drum (by a discharge lamp) and excess toner is cleaned off.

Max 5.

3Paper 1 style
(a)
Draw the logic circuit for X = (A NAND B) XOR (B OR C).
[3]
(b)
Complete the truth table for this expression.
[4]
Show mark scheme
(a)
  • A NAND gate with inputs A and B.
  • An OR gate with inputs B and C.
  • Both outputs feed into an XOR gate whose output is X.
(b)
ABCA NAND BB OR CX
000101
001110
010110
011110
100101
101110
110011
111011

4 marks for 8 correct rows of X; 3 marks for 6 or 7; 2 marks for 4 or 5; 1 mark for 2 or 3. You can check this with the truth table builder above.

4Paper 1 style

A greenhouse has three inputs: T is 1 when the temperature is too high, W is 1 when the window is open, and H is 1 when the humidity is too high. An alarm X sounds when the window is closed and either the temperature or the humidity is too high.

(a)
Write the logic expression for this problem statement.
[2]
(b)
Complete the truth table.
[4]
Show mark scheme
  • (a) X = (T OR H) AND NOT W; one mark for T OR H, one mark for AND NOT W.
  • Equivalent answers accepted, such as (T AND NOT W) OR (H AND NOT W).
TWHX
0000
0011
0100
0110
1001
1011
1100
1110
5Paper 1 style
(a)
Explain what is meant by an embedded system, giving an example.
[2]
(b)
Explain why a buffer is used when a computer sends a document to a printer.
[2]
Show mark scheme
  • (a) A computer system built into a larger device, designed to perform a dedicated function.
  • (a) Any suitable example: washing machine, microwave oven, car engine controller, set-top box, smart thermostat.
  • (b) The printer works much more slowly than the processor, so the data is stored temporarily in the buffer.
  • (b) The processor can send the whole document quickly and then continue with other tasks while the printer prints from the buffer.

The CPU fetches instructions from memory, decodes them and executes them, billions of times a second. You need to know the parts involved, the registers that hold values along the way, and how to read and trace simple assembly language.

The Von Neumann model

Almost all general-purpose computers follow the Von Neumann architecture. Its key idea is the stored program concept: program instructions and data are both stored in the same main memory, and instructions are fetched and executed one at a time, in sequence.

CPU Control Unit ALUarithmetic and logic RegistersPC MAR MDR CIR ACC IX SR System clock and cache Main memoryinstructions and data (IAS) Input and outputvia ports and controllers Address bus (one way) Data bus (two way) Control bus (two way)

Registers

A register is a very fast storage location inside the CPU. General-purpose registers hold any data the program is working with; special-purpose registers each have one job.

RegisterWhat it holds
PC Program CounterThe address of the next instruction to be fetched
MAR Memory Address RegisterThe address of the memory location about to be read from or written to
MDR Memory Data RegisterThe data or instruction just read from memory, or about to be written to it
CIR Current Instruction RegisterThe instruction currently being decoded and executed
ACC AccumulatorThe value being worked on; holds the results of ALU calculations
IX Index RegisterA value added to an address in indexed addressing, for example to step through an array
SR Status RegisterFlags (single bits) that record conditions such as carry, overflow, negative, zero, or an interrupt

Other components

Arithmetic Logic Unit
Carries out arithmetic (add, subtract) and logic operations (AND, OR, comparisons, shifts).
Control Unit
Decodes instructions and sends control signals to coordinate every other part of the CPU and the movement of data.
System clock
Produces timing signals at a fixed rate so that all components work in step.
Immediate Access Store
Main memory (RAM) that the CPU can access directly, holding the program and data in use.

Buses

BusDirectionCarries
Address busOne way: CPU to memoryThe address of the location to be read or written. Its width sets how many locations can be addressed: n lines give 2n addresses.
Data busTwo wayData and instructions between the CPU, memory and I/O. Its width is how many bits move in one go (the word size).
Control busTwo wayControl and timing signals, such as memory read, memory write, clock and interrupt request.

What affects CPU performance

  • Clock speed: more cycles per second means more instructions executed per second (but more heat).
  • Number of cores: each core can process instructions independently, so several tasks run at the same time. The software must be able to split its work for this to help.
  • Bus width: a wider data bus moves more bits per transfer; a wider address bus can address more memory.
  • Cache memory: fast memory close to the CPU holding frequently used instructions and data, so the CPU waits less for slower RAM. More cache means more hits.

Ports

USB
Universal Serial Bus. Connects many kinds of peripherals; devices are detected automatically and the right driver is loaded; supplies power; data travels serially.
HDMI
High Definition Multimedia Interface. Sends high-definition digital video and audio together to monitors and TVs; supports encryption to protect content.
VGA
Video Graphics Array. An older port that sends analogue video only, with no audio, so quality is lower at high resolutions.

The fetch-execute cycle

Register Transfer Notation (RTN) shows data moving between registers. Square brackets mean "the contents of", so [PC] is the value in the PC.

RTNWhat happens
MAR ← [PC]The address of the next instruction is copied from the PC into the MAR.
PC ← [PC] + 1The PC is incremented so it points to the next instruction.
MDR ← [[MAR]]The instruction at the address held in the MAR is sent along the data bus into the MDR.
CIR ← [MDR]The instruction is copied into the CIR.
The control unit decodes the instruction in the CIR (opcode and operand), then it is executed, for example by the ALU.

Interrupts

An interrupt is a signal to the processor that something needs attention. It can come from hardware (a key press, a printer out of paper), software (division by zero, a program requesting a service) or a timer.

  1. At the end of each fetch-execute cycle, the processor checks for an interrupt.
  2. If there is one with a higher priority than the current task, the contents of the registers (including the PC) are saved on a stack.
  3. The address of the correct Interrupt Service Routine (ISR) is loaded into the PC, and the ISR runs.
  4. When the ISR finishes, the saved register values are restored and the original task continues where it left off.

Assembly language

Machine code is binary instructions the processor runs directly. Assembly language replaces each binary opcode with a mnemonic such as LDD or ADD, so there is usually one assembly instruction per machine code instruction. An assembler translates it.

The two-pass assembler

  • Pass 1: reads the program line by line, removes comments, and builds a symbol table containing every label (symbolic address) and the address it stands for. Labels used before they are defined (forward references) are added and resolved later in the pass.
  • Pass 2: uses the symbol table to replace each label with its address, converts each opcode mnemonic to its binary opcode, and produces the object (machine) code.

Addressing modes

Immediate
The operand is the value to use. LDM #25 loads 25.
Direct
The operand is the address of the value. LDD 150 loads whatever is stored at address 150.
Indirect
The operand is an address that holds another address; the value is at that second address. LDI 150.
Indexed
The address used is the operand plus the contents of the IX. LDX 150 with IX = 3 loads from address 153.
Relative
The address is given as an offset from the current instruction's address, so code still works if it is moved in memory.

The instruction set used in 9618 papers

In operands, # means a denary value, B a binary value and & a hexadecimal value, such as #12, #B00001100, #&0C.

InstructionEffect
LDM #nLoad the number n into the ACC
LDD <address>Load the contents of the address into the ACC
LDI <address>Indirect: the address holds a second address; load the contents of the second address
LDX <address>Indexed: load the contents of (address + IX)
LDR #nLoad the number n into the IX
MOV <register>Copy the ACC into the given register (IX)
STO <address>Store the ACC at the address
ADD <address> / ADD #nAdd the contents of the address (or the number n) to the ACC
SUB <address> / SUB #nSubtract the contents of the address (or n) from the ACC
INC <register> / DEC <register>Add or subtract 1 from the ACC or IX
JMP <address>Jump to the address
CMP <address> / CMP #nCompare the ACC with the contents of the address (or with n)
CMI <address>Indirect compare: the address holds a second address; compare the ACC with its contents
JPE <address>After a compare, jump if the comparison was True (equal)
JPN <address>After a compare, jump if the comparison was False (not equal)
IN / OUTInput a character into the ACC as its ASCII code / output the character whose ASCII code is in the ACC
ENDReturn control to the operating system
AND, OR, XOR with #n or an addressBitwise operation between the ACC and the operand; result in the ACC
LSL #n / LSR #nShift the bits in the ACC n places left / right, filling with zeros

Worked example: tracing a program

This program adds up the whole numbers from the value at address 301 down to 1. Address 301 starts at 3.

100  LDM #0
101  STO 300
102  LDD 301
103  CMP #0
104  JPE 112
105  LDD 300
106  ADD 301
107  STO 300
108  LDD 301
109  DEC ACC
110  STO 301
111  JMP 102
112  LDD 300
113  END

Each loop adds the counter (301) to the total (300), then decreases the counter. When the counter reaches 0, the comparison at 103 is true and the program jumps to 112. The total ends as 3 + 2 + 1 = 6.

Bit manipulation

Shifts

Logical shift
Bits move left or right; the bit shifted out is lost and a 0 enters at the other end. A left shift of 1 multiplies an unsigned number by 2; a right shift divides by 2 (if no 1s are lost).
Arithmetic shift
Like a logical shift, but the sign bit is preserved, so it works correctly on two's complement numbers. On a right shift, the sign bit is copied into the space.
Cyclic shift
The bit shifted out of one end goes back in at the other end, so no bits are lost (also called a rotate).
StartOperationResult
1011 0110Logical shift left 10110 1100
1011 0110Logical shift right 20010 1101
1011 0110Arithmetic shift right 11101 1011
1011 0110Cyclic shift left 10110 1101

Masks

A mask is a bit pattern used with a logic operation to work on particular bits. This is how a control program checks or changes individual flags, for example one bit per sensor in a status byte.

ToUseMask bitsExample
Test a bitAND1 in the position to test, 0 elsewhereAND #B00001000: the result is non-zero only if bit 3 was 1
Clear bits to 0AND0 where bits are cleared, 1 to keepAND #B11110000 clears the lower nibble
Set bits to 1OR1 where bits are set, 0 to keepOR #B00000001 sets bit 0
Toggle bitsXOR1 where bits flip, 0 to keepXOR #B11111111 flips every bit

Exam-style questions

1Paper 1 style
Describe the stages of the fetch-execute cycle. You may use register transfer notation.
[5]
Show mark scheme
  • The address in the PC is copied to the MAR: MAR ← [PC]
  • The PC is incremented: PC ← [PC] + 1
  • The instruction at the address in the MAR is copied to the MDR using the data bus: MDR ← [[MAR]]
  • The contents of the MDR are copied to the CIR: CIR ← [MDR]
  • The control unit decodes the instruction in the CIR.
  • The instruction is executed.

Max 5.

2Paper 1 style
(a)
Explain how increasing the width of the data bus can improve the performance of a computer.
[2]
(b)
A computer has a 16-bit address bus. State the maximum number of memory locations it can address.
[1]
(c)
Explain why the address bus is unidirectional.
[1]
Show mark scheme
  • (a) More bits can be transferred at the same time (in each clock cycle).
  • (a) So fewer transfers are needed to move the same data, and instructions are fetched and executed faster.
  • (b) 216 = 65 536
  • (c) Addresses only ever travel from the CPU (MAR) to memory; memory never sends an address back.
3Paper 1 style

The table shows part of the memory. The index register (IX) contains 1.

AddressContents
150152
15133
15247
15318
State the contents of the ACC after each instruction is executed separately:
LDM #150, LDD 150, LDI 150, LDX 150
[4]
Show mark scheme
  • LDM #150 → 150 (immediate: the operand is the value)
  • LDD 150 → 152 (direct: contents of address 150)
  • LDI 150 → 47 (indirect: address 150 holds 152, and address 152 holds 47)
  • LDX 150 → 33 (indexed: 150 + IX of 1 = 151)
4Paper 1 style

Use the program in the worked example above. Address 300 initially contains 15 and address 301 contains 3.

(a)
Complete a trace table showing the instruction addresses executed and the contents of the ACC and of addresses 300 and 301.
[5]
(b)
State the purpose of the program.
[1]
Show mark scheme
InstructionACC300301
153
1000
1010
1023
1050
1063
1073
1083
1092
1102
1022
1053
1065
1075
1082
1091
1101
1021
1055
1066
1076
1081
1090
1100
1020
1126
  • (a) One mark per correct loop (three loops), one for the initial 0 stored at 300, one for the final jump to 112 with ACC = 6.
  • (b) It calculates the sum of the integers from the starting value in 301 down to 1 (here 3 + 2 + 1 = 6) and leaves it in the ACC and address 300.
5Paper 1 style

The ACC contains 1011 0110.

(a)
Write one instruction that sets the four most significant bits to 0 and leaves the others unchanged. Give the result.
[2]
(b)
Write one instruction that sets bit 0 (the least significant bit) to 1. Give the result.
[2]
(c)
Give the contents of the ACC after LSR #2 is applied to the original value.
[1]
Show mark scheme
  • (a) AND #B00001111 (or AND #&0F, AND #15)
  • (a) Result 0000 0110
  • (b) OR #B00000001 (or OR #1)
  • (b) Result 1011 0111
  • (c) 0010 1101
6Paper 1 style
Describe what happens during each pass of a two-pass assembler.
[4]
Show mark scheme
  • Pass 1: the source code is read line by line and comments and whitespace are removed.
  • Pass 1: a symbol table is built containing each label (symbolic address) and its address.
  • Pass 1: forward references are recorded and resolved once their labels are found.
  • Pass 2: each label is replaced with its address from the symbol table.
  • Pass 2: each mnemonic opcode is converted to its binary opcode, and the object code is generated.

Max 2 per pass.

System software runs the computer itself rather than doing a job for the user. The operating system manages the hardware and other programs; utilities keep the system healthy; translators turn source code into something the processor can run.

Why a computer needs an operating system

Without an OS, every application would have to control the hardware directly. The OS provides a user interface, hides the complexity of the hardware, and manages resources so several programs can run safely at once.

Management taskWhat the OS does
Memory managementAllocates memory to programs and data and frees it when they finish; keeps processes from overwriting each other's memory; uses virtual memory if RAM is full.
File managementOrganises files in a directory (folder) structure; handles naming, saving, opening, copying and deleting; controls file access permissions.
Security managementUser accounts and passwords; access rights; keeping the system updated against threats; firewall and backup provision.
Hardware management (input/output)Communicates with devices through drivers; handles interrupts from devices; manages queues and buffers, such as for a printer.
Process managementSchedules processes so the CPU is shared fairly (multitasking); starts and ends processes; handles deadlock and allows processes to communicate.

Utility software

Disk formatter
Prepares a disk for first use by dividing it into tracks and sectors and setting up a file system. It deletes existing data and can check for bad sectors.
Virus checker
Scans files and memory for viruses by comparing them with a database of known virus signatures, and by watching for suspicious behaviour (heuristics). Infected files are quarantined or deleted. It must be updated regularly.
Defragmentation software
Over time, files are split into fragments scattered across a hard disk. The defragmenter moves the fragments so each file is stored in contiguous sectors and free space is grouped together. The read/write head moves less, so files load faster. (Not needed on SSDs.)
Disk contents analysis and repair
Checks the disk for errors and bad sectors, marks them so they won't be used, and recovers data where possible. It also shows how the space is being used.
File compression
Reduces the size of files so they use less storage and are faster to send.
Back-up software
Makes copies of files on a schedule, often only those that changed since the last backup (incremental), so data can be restored if lost.

Program libraries

A program library is a collection of pre-written, pre-tested, ready-compiled routines (such as maths or graphics functions) that programmers can use in their own programs.

  • Benefits: saves development time; the code has already been tested, so it is more reliable; specialist routines can be used without the programmer having the expertise to write them.

Dynamic Link Libraries (DLLs)

A DLL file is linked to a program only when the program runs, rather than copied into the executable at compile time.

  • Benefits: executables are smaller; one copy in memory can be shared by several programs at once, saving RAM; the DLL can be updated without recompiling every program that uses it.
  • Drawbacks: if the DLL is missing, renamed or corrupted, the program won't run; an updated DLL may be incompatible with programs written for the old version; the program depends on something outside the programmer's control.

Language translators

Programs written in assembly or a high-level language must be translated into machine code. There are three kinds of translator.

Assembler
Translates assembly language into machine code, usually one machine instruction per assembly instruction.
Compiler
Translates the whole high-level program into an executable machine code file before it runs.
Interpreter
Translates and executes the program one statement at a time, without producing a separate executable file.
CompilerInterpreter
Translates the whole program in one goTranslates and runs one line at a time
Produces an executable file that runs without the compilerThe interpreter is needed every time the program runs
The compiled program runs fasterRuns more slowly, because each line is translated every time it is executed
Reports all errors at the end, so debugging can be harderStops at the first error, so the programmer can fix it and continue immediately
Source code can be kept secret, since only the executable is distributedThe source code must be supplied to users
Best for finished productsBest during development and learning

Partly compiled, partly interpreted: Java source code is compiled into bytecode, an intermediate form. The Java Virtual Machine then interprets (or just-in-time compiles) the bytecode on each computer. This makes the same compiled program portable to any platform with a JVM. Python works similarly.

Integrated Development Environments

An IDE is a single program that provides the tools needed to write, test and debug code.

PurposeFeatureHow it helps
CodingContext-sensitive promptsSuggests keywords, variable names and the parameters of a function as you type, so code is faster to write with fewer mistakes.
Initial error detectionDynamic syntax checksUnderlines syntax errors as soon as they are typed, before the program is translated.
PresentationPrettyprintColour-codes keywords, strings and comments and indents code automatically, making it easier to read.
PresentationExpand and collapse code blocksHides the body of procedures or loops so you can see the overall structure.
DebuggingSingle steppingExecutes the program one statement at a time so you can see exactly where it goes wrong.
DebuggingBreakpointsPauses execution at a chosen line so the program's state can be inspected at that point.
DebuggingReport (watch) windowShows the current values of variables and expressions as the program runs.

Exam-style questions

1Paper 1 style
Describe three management tasks carried out by an operating system.
[6]
Show mark scheme

One mark for naming each task, one for a valid description. Max 3 tasks.

  • Memory management: allocates memory to processes and frees it when finished; prevents processes from accessing each other's memory.
  • File management: provides a file and folder structure; controls creating, naming, saving, moving and deleting files.
  • Security management: controls user accounts and passwords; sets access rights; provides firewall or updates.
  • Hardware management: communicates with peripherals through device drivers; handles interrupts and buffers.
  • Process management: schedules processes so the CPU is shared; allows multitasking; manages deadlock.
2Paper 1 style
Explain how defragmentation software can improve the performance of a computer with a magnetic hard disk.
[3]
Show mark scheme
  • Over time, files are stored in fragments in non-contiguous sectors across the disk.
  • The software rearranges the fragments so each file is stored in contiguous sectors, and free space is gathered together.
  • The read/write head needs to move less to read a file, so files are accessed faster.
  • New files are less likely to be fragmented because free space is contiguous.

Max 3.

3Paper 1 style
(a)
Describe two differences between how a compiler and an interpreter translate a program.
[4]
(b)
Explain why a programmer might use an interpreter while developing a program, then a compiler when it is finished.
[2]
Show mark scheme
  • (a) A compiler translates the whole program before execution; an interpreter translates and executes one statement at a time.
  • (a) A compiler produces an executable (object code) file; an interpreter produces no executable file.
  • (a) A compiler reports all errors after translation; an interpreter stops at the first error found.
  • (a) Compiled code runs faster; interpreted code must be retranslated each time it runs.
  • (b) During development, an interpreter shows errors as soon as they are reached, so they can be fixed and the program continued straight away.
  • (b) Once finished, a compiler produces a fast executable that can be distributed without the source code or the translator.

(a) max 2 marks per difference, max 4.

4Paper 1 style
A program runs but produces the wrong output. Describe three features of an IDE that would help the programmer find the error.
[3]
Show mark scheme
  • Breakpoints: stop the program at a set point so the values of variables can be checked there.
  • Single stepping: run one statement at a time to follow the program's path.
  • Report/watch window: displays the values of variables as they change while the program runs.

Prettyprint and syntax checking don't help find logic errors, so they would not be credited here.

5Paper 1 style
Explain two benefits and one drawback of a program using Dynamic Link Library (DLL) files.
[3]
Show mark scheme
  • Benefit: the executable file is smaller, because the library code isn't included in it.
  • Benefit: one copy of the DLL in memory can be shared by several programs, saving memory.
  • Benefit: the DLL can be updated without recompiling the programs that use it.
  • Drawback: if the DLL is missing or corrupted, or a new version is incompatible, the program fails to run.

Three different ideas are easy to mix up in an exam: keeping data safe from loss and attack (security), controlling who may see personal data (privacy), and making sure data is accurate (integrity).

Security, privacy and integrity

Data security
Protecting data against loss, damage or unauthorised access, for example with backups, passwords and firewalls.
Data privacy
Keeping personal data from being seen or used by people who don't have the right to. Data protection laws require organisations to collect only necessary data, keep it accurate and secure, and use it only for the stated purpose.
Data integrity
Making sure data is accurate, complete and consistent: correct when entered and unchanged when stored or transmitted.

Data must be kept secure because it may be confidential (medical records, bank details), valuable to the organisation, or needed by law. Losing it can cause financial loss, legal action and damage to reputation.

Threats

Virus
Malicious code that attaches itself to a program or file and replicates when the host runs. It can delete or corrupt data, or make the computer unusable.
Worm
A standalone program that replicates itself across a network without needing a host file or user action, often using up bandwidth and resources.
Spyware
Secretly monitors the user, for example by recording keystrokes (a key logger), and sends the information to a third party, who may use it to steal passwords or bank details.
Hacking
Gaining unauthorised access to a computer system, possibly to steal, change or delete data.
Phishing
An email or message that appears to come from a trusted source and tries to trick the user into revealing personal data, often by following a link to a fake website.
Pharming
Malicious code installed on a computer or DNS server redirects the user from a genuine website to a fake one, even when the correct URL is typed.

Security measures

  • User accounts and access rights: each user logs in with their own account and can only read, write or delete the data their role allows.
  • Passwords: should be strong (long, mixed characters), changed regularly and never shared. Systems can lock an account after several failed attempts.
  • Authentication: proving who a user is, using passwords, biometrics (fingerprint, face, iris), two-factor authentication or digital signatures.
  • Firewall: hardware or software that monitors traffic between a network and the internet, and blocks traffic that doesn't meet a set of rules, such as from unauthorised IP addresses or ports.
  • Anti-virus and anti-spyware software: detect and remove malware; scan files in real time.
  • Encryption: scrambles data with a key so that, if it is intercepted or stolen, it cannot be understood without the key. It does not stop the data being intercepted.
  • Backup: copies of data stored separately (ideally off-site or in the cloud) so lost or corrupted data can be restored. Disk mirroring writes data to two disks at once.

Validation

Validation is an automatic check by the computer that data entered is reasonable and meets set rules. It can't check that data is actually correct: a valid date of birth could still be the wrong one.

CheckWhat it testsExample
Range checkThe value lies between a lower and upper limitA percentage is from 0 to 100
Limit checkThe value is above or below one limit onlyAge is at least 18
Format checkThe data follows a patternA product code is two letters then four digits
Length checkThe number of characters is correct or within limitsA password has at least 8 characters
Presence checkA required field isn't left emptyEmail address must be entered
Existence checkThe data matches an entry that already existsThe customer ID entered is in the customer table
Type checkThe data is of the expected data typeQuantity is an integer
Check digitAn extra digit calculated from the other digits is correctBarcodes, ISBNs

Check digit example (modulo 11)

For the code 3572, multiply each digit by a weight (5, 4, 3, 2) and add: 15 + 20 + 21 + 4 = 60. Find the remainder after dividing by 11: 60 MOD 11 = 5. The check digit is 11 − 5 = 6, so the full code is 35726. When the code is entered, the computer recalculates the check digit and compares. This catches most single-digit errors and transposed digits.

Verification

Verification checks that data has been copied accurately from one place to another: when typed in, or when transferred.

During data entry

  • Visual check: the user reads the data on screen and compares it with the original document.
  • Double entry: the data is entered twice (often by different people, or a password typed twice) and the computer compares the two entries.

During data transfer

  • Parity check: the sender and receiver agree on even or odd parity. A parity bit is set so that each byte has an even (or odd) number of 1s. The receiver counts the 1s in each byte; if the parity is wrong, an error has occurred. A single parity bit cannot detect an even number of bit errors in the same byte, and cannot show which bit is wrong.
  • Parity block (parity byte): data is sent in a block of bytes, each with a parity bit, plus a final parity byte that holds a parity bit for each column. If one bit is wrong, the faulty row and column cross at that bit, so it can be located and corrected.
  • Checksum: the sender calculates a value from the block of data using an agreed algorithm and sends it with the block. The receiver recalculates the checksum and compares; if they differ, the data is requested again.

Worked example: parity block with even parity

The first bit of each byte is the parity bit. One bit was changed in transmission.

P23456781s
Byte 1010110014
Byte 2101101004
Byte 3011101015
Byte 4100010114
Parity byte000101114
Column 1s22242324

Byte 3 has an odd number of 1s and column 6 has an odd number of 1s. They cross at byte 3, bit 6, so that bit is flipped back from 1 to 0. The corrected byte is 0111 0001.

Exam-style questions

1Paper 1 style
Explain the difference between data security and data integrity.
[2]
Show mark scheme
  • Data security is protecting data from loss, damage or unauthorised access.
  • Data integrity is ensuring that data is accurate, complete and consistent (unchanged from the original).
2Paper 1 style
Describe how phishing and pharming differ, and give one way a user can protect themselves from each.
[4]
Show mark scheme
  • Phishing uses a legitimate-looking email or message to trick the user into clicking a link or giving personal details.
  • Pharming uses malicious code on the computer or a DNS server to redirect the user to a fake website, even when the correct address is typed.
  • Phishing protection: don't click links in unexpected emails; check the sender's address; use a spam filter.
  • Pharming protection: use anti-malware software; check the website's digital certificate or HTTPS padlock; use a trusted DNS.
3Paper 1 style

A school's online form asks for a student's date of birth and a student ID made of 2 letters followed by 4 digits.

(a)
Identify and describe two different validation checks that could be used on the student ID.
[4]
(b)
Explain why validation does not guarantee the data entered is correct.
[1]
Show mark scheme
  • (a) Format check: checks that the first two characters are letters and the last four are digits.
  • (a) Length check: checks that exactly 6 characters were entered.
  • (a) Presence check: checks that the field is not empty.
  • (a) Existence check: checks that the ID matches an existing student record.
  • (b) Validation only checks that data is reasonable or follows rules; a valid ID could still belong to a different student (be the wrong one).

(a) One mark for naming the check, one for describing it on this ID. Max 2 checks.

4Paper 1 style

Four bytes and a parity byte were received. Even parity is used, and the first bit of each byte is the parity bit.

Byte 11100 0011
Byte 20101 1101
Byte 31011 0001
Byte 40110 1111
Parity byte0100 1000
(a)
One bit has been changed during transmission. Identify the byte and the bit (counting bit 1 as the leftmost) that are in error, and write the corrected byte. Explain how you found them.
[3]
(b)
Explain why a single parity bit per byte might not detect an error.
[1]
Show mark scheme

Count the 1s. Rows: byte 1 = 4, byte 2 = 5, byte 3 = 4, byte 4 = 6, parity byte = 2. Columns 1 to 8: 2, 4, 2, 2, 3, 2, 2, 4.

  • (a) Byte 2 has an odd number of 1s, so the error is in byte 2.
  • (a) Column 5 has an odd number of 1s, so the error is in bit 5.
  • (a) The bit where they cross is flipped from 1 to 0: the corrected byte is 0101 0101.
  • (b) If an even number of bits in one byte change, the count of 1s stays even, so the parity still appears correct.
5Paper 1 style
Describe how a checksum is used to verify that a block of data has been transmitted correctly.
[3]
Show mark scheme
  • Before sending, the sender calculates a checksum value from the block of data using an agreed algorithm.
  • The checksum is transmitted with the block.
  • The receiver recalculates the checksum from the received data using the same algorithm and compares it with the one sent.
  • If they don't match, an error has occurred and the block is resent.

Max 3.

Computer professionals make decisions that affect clients, users and the public. This topic covers the codes of conduct they follow, who owns software and creative work, the licences that control how software can be used, and the effects of artificial intelligence.

Ethics and professional codes

Ethics are the moral principles that guide behaviour. Professional bodies publish codes of conduct so that members know what is expected of them, the public can trust them, and there is a standard against which bad practice can be judged.

The ACM/IEEE Software Engineering Code of Ethics

It sets out eight principles. Software engineers should act:

PrincipleMeaning
PublicConsistently with the public interest, including health, safety and the environment
Client and employerIn the best interests of the client and employer, consistent with the public interest
ProductEnsuring their products meet the highest professional standards possible, and are properly tested
JudgementWith integrity and independence in their professional judgement
ManagementManagers should promote an ethical approach to managing software development
ProfessionAdvancing the integrity and reputation of the profession
ColleaguesBeing fair to and supportive of colleagues
SelfContinuing to learn throughout their career and promoting ethical practice

The BCS (the British Computer Society) code of conduct covers similar ground under four headings: the public interest, professional competence and integrity, duty to the relevant authority, and duty to the profession.

Exam tipScenario questions describe a situation (for example being asked to release software with known bugs, or to copy a competitor's code). Name the principle, then say specifically what the person should or shouldn't do in that scenario.

Copyright and ownership

Copyright gives the creator of an original work (program code, music, text, images) legal ownership of it. Copyright law makes it illegal to copy, modify, distribute or sell the work without the owner's permission.

  • Why it is needed: creators invest time and money and need to be rewarded; it encourages innovation; it stops others profiting from work they didn't do.
  • How software is protected: licence agreements, product keys or activation codes, online authentication, digital watermarks, and distributing only compiled code.
  • Plagiarism: presenting someone else's work as your own, which is unethical even when it isn't illegal.

Software licences

LicenceCostSource codeCan users modify and share it?
Free software (Free Software Foundation)Usually free, but "free" means freedom, not priceSuppliedYes: freedom to run, study, change and redistribute. Copies and changed versions must keep the same freedoms.
Open source (Open Source Initiative)Usually freeSuppliedYes, under the terms of the licence. Focuses on the practical benefits of shared, collaborative development.
SharewareFree to try, then payNot suppliedCan share the trial copy; cannot modify. The trial may be time-limited or have reduced features.
CommercialMust be bought (or subscribed to)Not suppliedNo. The licence limits the number of users or devices; copying is illegal.

Artificial intelligence and its impact

Artificial intelligence (AI) is the ability of a computer system to perform tasks that normally need human intelligence, such as recognising speech and images, making decisions, and learning from data.

AreaPositive impactsNegative impacts
SocialFaster, more accurate medical diagnosis; assistive technology for people with disabilities; safer cars with collision avoidanceBias in training data can lead to unfair decisions (in hiring or loans); privacy concerns from surveillance; deepfakes and misinformation; over-reliance on AI decisions
EconomicIncreased productivity; 24/7 automated services; new jobs in AI development and maintenanceJobs lost to automation, especially repetitive tasks; benefits concentrated in a few companies; cost of retraining
EnvironmentalOptimises energy use in buildings and power grids; better climate modelling; reduces waste in farming and manufacturingTraining and running large models uses a lot of electricity and water for data centres; electronic waste from hardware

Exam-style questions

1Paper 1 style

Aisha is a software engineer. Her manager asks her to release a banking app on time, even though testing has found a bug that sometimes shows the wrong account balance.

Identify two principles of the ACM/IEEE Software Engineering Code of Ethics that apply, and explain how each should guide Aisha's actions.
[4]
Show mark scheme
  • Product: she should make sure the software meets high standards and is fully tested before release.
  • So she should not release the app with a known bug; she should report it and fix it first.
  • Public: releasing it could harm the public (users could make financial decisions on wrong balances).
  • Judgement: she should maintain her professional integrity and not simply follow the instruction against her judgement.
  • Client and employer: releasing a faulty product would damage the bank's (client's) interests and reputation.

One mark for each principle identified, one for each linked explanation. Max 4.

2Paper 1 style
Compare open source software and shareware.
[4]
Show mark scheme
  • Open source provides the source code; shareware does not.
  • Open source users can modify the code; shareware users cannot.
  • Open source is usually free to use permanently; shareware is free only for a trial period, or has limited features, then must be paid for.
  • Open source can be redistributed, including modified versions; shareware trial copies may be shared but not changed.
3Paper 1 style
A supermarket chain is introducing AI-powered self-checkouts and automated stock control. Explain one economic impact and one social impact of this change.
[4]
Show mark scheme
  • Economic: fewer cashiers and stock staff are needed, so wage costs fall…
  • …but jobs are lost, or staff must be retrained for new roles such as maintaining the systems.
  • Economic: more accurate stock ordering reduces waste and increases profit.
  • Social: customers have less human contact, which may disadvantage elderly or less confident users.
  • Social: cameras and data collection raise privacy concerns about how customer data is used.

One mark for each impact, one for its expansion. Max 2 per impact.

A relational database stores data in linked tables so each fact is recorded once. You need the vocabulary, the skill of normalising a design to third normal form, and enough SQL to create tables and query them.

Why not just use files?

In a file-based system, each department or program keeps its own data files. This causes:

  • Data redundancy: the same data is stored in several files, which wastes storage.
  • Data inconsistency: when data changes in one file but not another, the copies disagree.
  • Data dependence: programs are tied to the structure of their files, so changing a file's structure means changing every program that uses it.
  • Poor security and sharing: it is hard to control who sees what, and hard to combine data from different files.

A relational database solves these by storing each item of data once, in linked tables, managed by a DBMS.

Relational database terms

Entity
Anything about which data is stored, such as a student or a book.
Table (relation)
A set of data about one type of entity, arranged in rows and columns.
Record (tuple)
One row of a table: the data about one instance of the entity.
Field (attribute)
One column of a table: one item of data about each entity.
Primary key
A field (or combination of fields) that uniquely identifies each record.
Candidate key
Any field or combination that could be chosen as the primary key.
Secondary key
A candidate key not chosen as the primary key, or a field indexed to allow fast searching.
Composite key
A primary key made of two or more fields.
Foreign key
A field in one table that is the primary key of another table, used to link the two.
Referential integrity
Every foreign key value must match an existing primary key value in the linked table. You can't add a loan for a member who doesn't exist, or delete a member who still has loans.
Indexing
A separate structure that stores key values and the location of each record, so records can be found quickly without reading the whole table.

Relationships and E-R diagrams

Relationships can be one-to-one (1:1), one-to-many (1:M) or many-to-many (M:M). A many-to-many relationship can't be built directly; it is resolved with a link table, which turns it into two one-to-many relationships.

MEMBER LOAN BOOK one member has many loans one book has many loans
Crow's foot notation: the forked end is the "many" side. Members and books have a many-to-many relationship, resolved by the LOAN link table.

Normalisation

Normalisation is the process of organising data into tables to remove redundancy and the problems it causes when inserting, updating or deleting data.

First normal form (1NF)
No repeating groups of attributes; every field holds a single (atomic) value; there is a primary key.
Second normal form (2NF)
In 1NF, and no partial dependencies: every non-key field depends on the whole primary key, not just part of a composite key. (A table with a single-field key that is in 1NF is automatically in 2NF.)
Third normal form (3NF)
In 2NF, and no non-key (transitive) dependencies: no non-key field depends on another non-key field.

Worked example

An unnormalised table records orders. One order can contain many products, so the product fields repeat:

ORDER(OrderNo, OrderDate, CustomerID, CustomerName, {ProductID, Description, UnitPrice, Quantity})

To 1NF: remove the repeating group so each row holds one product of one order. The primary key becomes the composite key OrderNo + ProductID.

ORDER(OrderNo, ProductID, OrderDate, CustomerID, CustomerName, Description, UnitPrice, Quantity)

To 2NF: look for fields that depend on only part of the key. OrderDate, CustomerID and CustomerName depend only on OrderNo. Description and UnitPrice depend only on ProductID. Only Quantity needs both.

ORDER(OrderNo, OrderDate, CustomerID, CustomerName)
PRODUCT(ProductID, Description, UnitPrice)
ORDER_LINE(OrderNo, ProductID, Quantity)

To 3NF: CustomerName depends on CustomerID, which is not the key of ORDER. Move it to its own table.

CUSTOMER(CustomerID, CustomerName)
ORDER(OrderNo, OrderDate, CustomerID*)
PRODUCT(ProductID, Description, UnitPrice)
ORDER_LINE(OrderNo*, ProductID*, Quantity)

Underlined fields are primary keys; * marks a foreign key.

Database Management Systems

A DBMS is software that controls access to the database and addresses the problems of file-based systems.

Data dictionary
Stores the metadata: the name of every table and field, data types, field sizes, validation rules, primary and foreign keys, relationships and access rights.
Data modelling
Tools for designing and analysing the structure of the data, such as E-R diagrams.
Logical schema
The overall design of the database, showing the tables, fields and relationships, independent of how the data is stored physically.
Data integrity
Enforces validation rules and referential integrity; manages concurrent access so two users don't overwrite each other's changes (record locking).
Data security
Usernames and passwords, access rights for different users, automatic backups, encryption, and audit trails.
Developer interface
Lets developers create and manipulate the database without writing everything in SQL, for example tools to build tables, forms and reports.
Query processor
Takes a query written in SQL (or built in a query-by-example interface), checks it, optimises it, and runs it on the database.

SQL: defining the database (DDL)

Data Definition Language creates and changes the structure of a database. Data types in the syllabus: CHARACTER, VARCHAR(n), BOOLEAN, INTEGER, REAL, DATE, TIME.

CREATE DATABASE Library;

CREATE TABLE MEMBER (
    MemberID   CHARACTER(5),
    FirstName  VARCHAR(30),
    LastName   VARCHAR(30),
    DateJoined DATE,
    PRIMARY KEY (MemberID)
);

CREATE TABLE LOAN (
    LoanID    INTEGER,
    MemberID  CHARACTER(5),
    BookID    CHARACTER(6),
    LoanDate  DATE,
    Returned  BOOLEAN,
    PRIMARY KEY (LoanID),
    FOREIGN KEY (MemberID) REFERENCES MEMBER(MemberID)
);

ALTER TABLE MEMBER ADD Email VARCHAR(60);
ALTER TABLE LOAN ADD FOREIGN KEY (BookID) REFERENCES BOOK(BookID);

SQL: querying and changing data (DML)

Data Manipulation Language adds, changes, deletes and retrieves the data.

-- Titles and prices of science books, cheapest first
SELECT Title, Price
FROM BOOK
WHERE Genre = 'Science' AND Price < 20
ORDER BY Price ASC;

-- How many books in each genre
SELECT Genre, COUNT(BookID)
FROM BOOK
GROUP BY Genre;

-- Total value and average price of all books
SELECT SUM(Price), AVG(Price) FROM BOOK;

-- Names of members with a book not yet returned, with the book title
SELECT MEMBER.FirstName, MEMBER.LastName, BOOK.Title
FROM MEMBER
INNER JOIN LOAN ON MEMBER.MemberID = LOAN.MemberID
INNER JOIN BOOK ON LOAN.BookID = BOOK.BookID
WHERE LOAN.Returned = FALSE;

INSERT INTO MEMBER (MemberID, FirstName, LastName, DateJoined)
VALUES ('M0042', 'Sara', 'Khan', '2026-09-01');

UPDATE BOOK SET Price = 12.50 WHERE BookID = 'B00123';

DELETE FROM LOAN WHERE Returned = TRUE;
Exam tipStrings and dates go in quotes; numbers and Booleans don't. When fields with the same name appear in two tables, prefix them with the table name, as in LOAN.MemberID. Mark schemes also accept joins written as FROM MEMBER, LOAN WHERE MEMBER.MemberID = LOAN.MemberID.

Exam-style questions

1Paper 1 style
A shop stores its customer data in separate files for sales and for deliveries. Explain three limitations of this file-based approach.
[3]
Show mark scheme
  • Data redundancy: customer details are stored in both files, wasting storage.
  • Data inconsistency: if a customer's address is changed in one file but not the other, the files disagree.
  • Data dependence: the programs depend on the file structures, so changing a file means rewriting its programs.
  • Difficult to control access or combine data from the two files.

Max 3.

2Paper 1 style

A school records which clubs students attend. A student can attend many clubs. Each tutor group has one tutor.

STUDENT_CLUB(StudentID, StudentName, TutorGroup, TutorName, {ClubID, ClubName, ClubDay})

(a)
Explain why the table is not in first normal form.
[1]
(b)
Normalise the data to third normal form. Show the primary key of each table.
[5]
Show mark scheme
  • (a) It contains a repeating group: ClubID, ClubName and ClubDay repeat for each club a student attends.
  • (b) STUDENT(StudentID, StudentName, TutorGroup*)
  • (b) TUTOR_GROUP(TutorGroup, TutorName)
  • (b) CLUB(ClubID, ClubName, ClubDay)
  • (b) STUDENT_CLUB(StudentID, ClubID) link table with a composite key
  • (b) All primary keys correctly identified.

TutorName depends on TutorGroup (a non-key dependency), so it is moved out of STUDENT for 3NF.

3Paper 1 style

A library database has the tables MEMBER, BOOK and LOAN shown in the notes above. BOOK has the fields BookID, Title, Author, Genre and Price.

(a)
Write an SQL script to create the BOOK table. BookID is the primary key and is always 6 characters. Title has up to 50 characters, Author up to 40 and Genre up to 20.
[4]
(b)
Write an SQL script to display the title and author of every book written by 'R Ahmed', in alphabetical order of title.
[3]
(c)
Write an SQL script to display the number of loans made by each member, showing the MemberID.
[3]
Show mark scheme
CREATE TABLE BOOK (
    BookID  CHARACTER(6),
    Title   VARCHAR(50),
    Author  VARCHAR(40),
    Genre   VARCHAR(20),
    Price   REAL,
    PRIMARY KEY (BookID)
);
  • (a) CREATE TABLE BOOK with brackets
  • (a) BookID as CHARACTER(6)
  • (a) Title, Author, Genre as VARCHAR with the right sizes, and Price as REAL
  • (a) PRIMARY KEY (BookID)
SELECT Title, Author
FROM BOOK
WHERE Author = 'R Ahmed'
ORDER BY Title;
  • (b) SELECT Title, Author FROM BOOK
  • (b) WHERE Author = 'R Ahmed'
  • (b) ORDER BY Title (ASC optional)
SELECT MemberID, COUNT(LoanID)
FROM LOAN
GROUP BY MemberID;
  • (c) SELECT MemberID, COUNT(…)
  • (c) FROM LOAN
  • (c) GROUP BY MemberID
4Paper 1 style
(a)
Explain what is meant by referential integrity, using the MEMBER and LOAN tables as an example.
[2]
(b)
State two items of data stored in a DBMS data dictionary.
[2]
Show mark scheme
  • (a) Every foreign key value must match a primary key value that exists in the linked table…
  • (a) …so a LOAN record cannot have a MemberID that isn't in MEMBER, and a member with loans cannot be deleted.
  • (b) Any two: table names; field names; data types; field sizes; validation rules; primary/foreign keys; relationships; access rights.

Before writing code you need a clear plan. This topic covers the thinking skills used to break a problem down, and the three ways of writing an algorithm that Paper 2 expects: structured English, flowcharts and pseudocode.

Computational thinking

Abstraction
Removing unnecessary detail and keeping only what is essential to solve the problem. A metro map is an abstraction: it shows stations and connections but not exact distances or streets.
Decomposition
Breaking a complex problem into smaller sub-problems that are easier to understand and solve. Each sub-problem can become a module (procedure or function).

Benefits of abstraction: it reduces complexity, so the solution is quicker to design and program; the program is smaller and needs less memory; and the design focuses on what the user actually needs. Benefits of decomposition: modules can be written by different people at the same time, tested separately, and reused in other programs.

What an algorithm is

An algorithm is a solution to a problem expressed as a sequence of clearly defined steps. Every algorithm is built from three basic constructs: sequence (steps in order), selection (choosing a path with IF or CASE) and iteration (repeating with a loop).

Identifier tables

Before writing pseudocode, list every variable you'll need. Exam questions often ask you to complete one.

IdentifierData typeDescription
NumINTEGERThe number most recently input
MaxINTEGERThe largest number input so far
CountINTEGERLoop counter, the number of values input

One algorithm, three ways

Problem: input 10 integers and output the largest.

Structured English

A restricted form of English using short, numbered statements and command words.

1. INPUT the first number and store it as the largest so far
2. REPEAT 9 times
     INPUT a number
     IF the number is greater than the largest so far
        THEN store it as the largest so far
3. OUTPUT the largest

Flowchart

START INPUT Num Max ← NumCount ← 1 Count = 10? OUTPUT Max STOP INPUT Num Num > Max? Max ← Num Count ← Count + 1 YesNo YesNo
Rounded boxes are terminators (start and stop), parallelograms are input or output, rectangles are processes, and diamonds are decisions with exactly two labelled exits.

Pseudocode

DECLARE Num, Max, Count : INTEGER
INPUT Num
Max ← Num
FOR Count ← 2 TO 10
    INPUT Num
    IF Num > Max THEN
        Max ← Num
    ENDIF
NEXT Count
OUTPUT "The largest number is ", Max
Why not start Max at 0?

If every number input were negative, 0 would wrongly be output as the largest. Using the first input as the starting value always works. The same idea applies to finding a minimum.

Stepwise refinement

Stepwise refinement means taking each step of an outline algorithm and breaking it into more detailed steps, repeatedly, until each step can be written directly as a line of code. It is decomposition applied to the algorithm itself.

1. Get valid marks for 30 students
   1.1 FOR each of 30 students
       1.1.1 INPUT a mark
       1.1.2 WHILE the mark is not between 0 and 100
             OUTPUT an error message and INPUT the mark again
       1.1.3 Add the mark to the total
2. Calculate the average
   2.1 Average = total / 30
3. Output the average, rounded to 1 decimal place

Exam-style questions

1Paper 2 style
A programmer is writing a satellite navigation app. Explain what is meant by abstraction, and give one example of how it could be used in this app.
[3]
Show mark scheme
  • Abstraction is removing (or hiding) unnecessary details from a problem…
  • …keeping only the details that are essential to solve it.
  • Example: the map shows only roads, junctions, speed limits and destinations, and leaves out buildings, trees or road surface details.
2Paper 2 style
Write an algorithm in pseudocode that inputs the midday temperatures (as real numbers) for 30 days. It outputs the highest temperature, the lowest temperature and the average temperature.
[6]
Show mark scheme
DECLARE Temp, Highest, Lowest, Total : REAL
DECLARE Day : INTEGER
INPUT Temp
Highest ← Temp
Lowest ← Temp
Total ← Temp
FOR Day ← 2 TO 30
    INPUT Temp
    IF Temp > Highest THEN
        Highest ← Temp
    ENDIF
    IF Temp < Lowest THEN
        Lowest ← Temp
    ENDIF
    Total ← Total + Temp
NEXT Day
OUTPUT "Highest: ", Highest
OUTPUT "Lowest: ", Lowest
OUTPUT "Average: ", Total / 30
  • Variables declared and initialised (Total, Highest and Lowest set sensibly)
  • Loop that runs exactly 30 times (in total)
  • Input of temperature inside the loop
  • Correct comparison and update of the highest
  • Correct comparison and update of the lowest
  • Running total, then average calculated after the loop, and all three values output

Setting Highest to −999 and Lowest to 999 is also accepted, as long as the values are outside any likely temperature.

3Paper 2 style

This algorithm is described in structured English:

1. Set the count of passes to zero
2. Repeat for each of 25 students:
     input the student's mark
     if the mark is 40 or more, add 1 to the count of passes
3. Output the count of passes and the percentage of students who passed
(a)
Write the algorithm in pseudocode.
[5]
(b)
Complete an identifier table for your algorithm.
[3]
Show mark scheme
DECLARE Passes, Student, Mark : INTEGER
Passes ← 0
FOR Student ← 1 TO 25
    INPUT Mark
    IF Mark >= 40 THEN
        Passes ← Passes + 1
    ENDIF
NEXT Student
OUTPUT "Passes: ", Passes
OUTPUT "Percentage passed: ", Passes / 25 * 100
  • (a) Passes initialised to 0
  • (a) Count-controlled loop for 25 iterations
  • (a) INPUT Mark inside the loop
  • (a) IF Mark >= 40 then increment the count
  • (a) Output the count and percentage after the loop
  • (b) One mark per correct row: Passes INTEGER (number of students who passed); Student INTEGER (loop counter); Mark INTEGER (mark input for the current student).
4Paper 2 style
Explain how stepwise refinement helps a programmer design a solution.
[2]
Show mark scheme
  • The problem is broken down into smaller steps, and each step is repeatedly broken down into more detail…
  • …until each step is simple enough to be coded directly as program statements, which makes each part easier to design, code and test.

Choosing the right way to store data makes an algorithm simpler. This topic covers the basic data types, records, arrays, text files and three abstract data types: the stack, the queue and the linked list.

Data types

TypeHoldsExample
INTEGERWhole numbers42, −7
REALNumbers with a fractional part3.142, −0.5
CHARA single character, in single quotes'A'
STRINGZero or more characters, in double quotes"Lahore", ""
BOOLEANTRUE or FALSEFALSE
DATEA date12/11/2026
Exam tipPhone numbers, ID codes and postcodes are STRING, not INTEGER: they can start with 0, may contain spaces or symbols, and you never do arithmetic with them.

Records

A record is a composite, user-defined data type that groups related items of data, possibly of different types, under one identifier. Each item is a field.

TYPE StudentRecord
    DECLARE StudentID : STRING
    DECLARE Name : STRING
    DECLARE Mark : INTEGER
    DECLARE Paid : BOOLEAN
ENDTYPE

DECLARE Student : StudentRecord
Student.Name ← "Hira"
Student.Mark ← 78

// An array of records stores a whole class
DECLARE Class : ARRAY[1:30] OF StudentRecord
Class[1].Mark ← 65

Arrays

An array is a fixed-size, ordered collection of elements of the same data type, accessed by an index. The lower bound and upper bound are the first and last index values.

DECLARE Scores : ARRAY[1:10] OF INTEGER          // 1D: 10 elements
DECLARE Board : ARRAY[1:3, 1:3] OF CHAR          // 2D: 3 rows × 3 columns
DECLARE Row, Col : INTEGER

FOR Row ← 1 TO 3                                 // nested loops visit every element
    FOR Col ← 1 TO 3
        Board[Row, Col] ← ' '
    NEXT Col
NEXT Row

Linear search

Check each element in turn from the start until the item is found or the end is reached. It works on unsorted data.

DECLARE Index : INTEGER
DECLARE Found : BOOLEAN
Found ← FALSE
Index ← 1
WHILE Index <= 100 AND Found = FALSE
    IF Names[Index] = SearchName THEN
        Found ← TRUE
    ELSE
        Index ← Index + 1
    ENDIF
ENDWHILE
IF Found = TRUE THEN
    OUTPUT "Found at position ", Index
ELSE
    OUTPUT "Not found"
ENDIF

Bubble sort

Compare each pair of neighbouring elements and swap them if they are in the wrong order. After each pass the largest remaining value has "bubbled" to the end, so the next pass can stop one place earlier. A flag records whether any swap happened; if a pass makes no swaps, the array is sorted and the algorithm stops early.

DECLARE Top, J, Temp : INTEGER
DECLARE Swapped : BOOLEAN
Top ← 9                                  // array Numbers[1:10]
REPEAT
    Swapped ← FALSE
    FOR J ← 1 TO Top
        IF Numbers[J] > Numbers[J + 1] THEN
            Temp ← Numbers[J]
            Numbers[J] ← Numbers[J + 1]
            Numbers[J + 1] ← Temp
            Swapped ← TRUE
        ENDIF
    NEXT J
    Top ← Top - 1
UNTIL Swapped = FALSE OR Top = 0

Text files

Data in variables is lost when a program ends. Files store data permanently in secondary storage so it can be used again later or by another program.

// Write (creates the file, or overwrites an existing one)
OPENFILE "Scores.txt" FOR WRITE
WRITEFILE "Scores.txt", "Ali,72"
CLOSEFILE "Scores.txt"

// Append (adds to the end of an existing file)
OPENFILE "Scores.txt" FOR APPEND
WRITEFILE "Scores.txt", "Bina,85"
CLOSEFILE "Scores.txt"

// Read every line until the end of the file
DECLARE Line : STRING
OPENFILE "Scores.txt" FOR READ
WHILE NOT EOF("Scores.txt")
    READFILE "Scores.txt", Line
    OUTPUT Line
ENDWHILE
CLOSEFILE "Scores.txt"
Common mistakeUse a pre-condition (WHILE) loop when reading a file. A REPEAT loop would try to read once even if the file is empty.

Abstract data types

An abstract data type (ADT) is a collection of data together with a set of operations on that data, described by what it does rather than how it is implemented. At AS you need to know three, and how each can be built from an array and pointers.

Stack (last in, first out)

Items are added (pushed) and removed (popped) at the same end, the top. Uses: storing return addresses when subroutines are called, undo features, backtracking, evaluating expressions.

[6][5][4][3][2][1] 84217 TopPointer = 3 BasePointer = 1
PROCEDURE Push(NewItem : INTEGER)
    IF TopPointer = 6 THEN
        OUTPUT "Stack full"
    ELSE
        TopPointer ← TopPointer + 1
        Stack[TopPointer] ← NewItem
    ENDIF
ENDPROCEDURE

FUNCTION Pop() RETURNS INTEGER
    DECLARE Item : INTEGER
    IF TopPointer = 0 THEN
        OUTPUT "Stack empty"
        RETURN -1
    ELSE
        Item ← Stack[TopPointer]
        TopPointer ← TopPointer - 1
        RETURN Item
    ENDIF
ENDFUNCTION

Queue (first in, first out)

Items join at the rear and leave from the front. Uses: print queues, keyboard buffers, scheduling processes. In a circular queue, when the rear pointer reaches the end of the array it wraps round to the start, so spaces freed at the front are reused.

[1][2][3][4][5][6][7][8] P1P2P3P4 FrontPointer = 3 RearPointer = 6

Linked list

Each node holds data and a pointer to the next node. A start pointer gives the first node, and the last node has a null pointer. Items can be kept in order without moving data around: inserting or deleting only changes pointers. Unused nodes are kept in a free list with its own heap (free) pointer.

Start Ali Bina Omar∅ datapointer
In an array implementation, each node is an element of an array of records with a Data field and a Pointer field holding the index of the next node. A pointer of −1 (or 0) means null.

Exam-style questions

1Paper 2 style

A gym stores data about each member: a membership number such as "GYM0451", the member's phone number, date of joining, monthly fee, and whether they have paid this month.

(a)
Write pseudocode to declare a record type MemberRecord to hold this data, using a suitable data type for each field.
[5]
(b)
Write pseudocode to declare an array Members to hold 200 records, and to set the fee of the first member to 3500.
[2]
Show mark scheme
TYPE MemberRecord
    DECLARE MemberNo : STRING
    DECLARE Phone : STRING
    DECLARE DateJoined : DATE
    DECLARE MonthlyFee : REAL
    DECLARE Paid : BOOLEAN
ENDTYPE

DECLARE Members : ARRAY[1:200] OF MemberRecord
Members[1].MonthlyFee ← 3500
  • (a) TYPE MemberRecord … ENDTYPE
  • (a) MemberNo and Phone as STRING
  • (a) DateJoined as DATE
  • (a) MonthlyFee as REAL (INTEGER accepted if justified)
  • (a) Paid as BOOLEAN
  • (b) Correct array declaration with bounds 1 to 200 (or 0 to 199) of MemberRecord
  • (b) Members[1].MonthlyFee ← 3500
2Paper 2 style

A global 1D array Stock of type STRING has 50 elements, indexed 1 to 50, holding item names.

Write a function FindItem() that takes an item name as a parameter and returns the index of that item in the array, or −1 if it is not found. The search must stop as soon as the item is found.
[6]
Show mark scheme
FUNCTION FindItem(ItemName : STRING) RETURNS INTEGER
    DECLARE Index : INTEGER
    Index ← 1
    WHILE Index <= 50
        IF Stock[Index] = ItemName THEN
            RETURN Index
        ENDIF
        Index ← Index + 1
    ENDWHILE
    RETURN -1
ENDFUNCTION
  • Function heading with a STRING parameter and RETURNS INTEGER
  • Index declared and initialised
  • Conditional loop through the 50 elements
  • Correct comparison of the array element with the parameter
  • Returns the index as soon as it is found (or a flag ends the loop)
  • Returns −1 after the loop if not found
3Paper 2 style

The text file Names.txt contains one name on each line.

Write pseudocode that reads the file and outputs how many names begin with the letter 'A' (upper or lower case).
[5]
Show mark scheme
DECLARE Name : STRING
DECLARE Count : INTEGER
Count ← 0
OPENFILE "Names.txt" FOR READ
WHILE NOT EOF("Names.txt")
    READFILE "Names.txt", Name
    IF TO_UPPER(LEFT(Name, 1)) = "A" THEN
        Count ← Count + 1
    ENDIF
ENDWHILE
CLOSEFILE "Names.txt"
OUTPUT Count, " names begin with A"
  • Open the file for READ and close it at the end
  • Loop until EOF
  • READFILE inside the loop
  • Extract and test the first character, handling both cases
  • Count initialised, incremented and output after the loop
4Paper 2 style

A stack is implemented with the array Stack[1:6] and a variable TopPointer. It currently contains 17 (at index 1), 42 and 8, so TopPointer is 3, as in the diagram above.

(a)
These operations are carried out in order: Push(25), Pop(), Pop(), Push(11). State the contents of the stack and the value of TopPointer afterwards.
[3]
(b)
Explain why a stack is described as a LIFO data structure.
[1]
Show mark scheme
  • (a) Push 25 → 17, 42, 8, 25. Pop removes 25. Pop removes 8. Push 11 → 17, 42, 11.
  • (a) Final contents from index 1: 17, 42, 11
  • (a) TopPointer = 3
  • (b) Last In, First Out: the most recently added item is the first one removed.

Popped values may still be physically in the array; credit answers that make clear they are no longer part of the stack.

5Paper 2 style

An array contains the values 5, 1, 4, 2, 8 (in that order). It is sorted into ascending order with a bubble sort.

(a)
Write the contents of the array after the first pass.
[1]
(b)
Explain how using a flag can make a bubble sort more efficient.
[2]
Show mark scheme
  • (a) 1, 4, 2, 5, 8
  • (b) The flag records whether any swaps were made during a pass.
  • (b) If a pass completes with no swaps the data is already sorted, so the algorithm stops instead of doing unnecessary passes.

Try it in the sorting tool above with the values 5 1 4 2 8.

Paper 2 is written in Cambridge pseudocode. Exact syntax matters less than clear logic, but using the standard keywords makes your answers easy to mark. This page is your reference for the syntax and the built-in functions.

Variables, constants and assignment

DECLARE Total : INTEGER
DECLARE Price, Discount : REAL
DECLARE Name : STRING
CONSTANT VAT = 0.17                // a constant can't change while the program runs

Total ← 0                          // assignment uses the arrow ←
INPUT Name
OUTPUT "Hello ", Name              // OUTPUT can take several items

Use a constant for a value that never changes during the run (a tax rate, the size of an array). If the value must change one day, it only needs editing in one place, and the program is easier to read.

Operators

ArithmeticRelationalLogical and string
+ − * /= equal, <> not equalAND, OR, NOT
DIV integer division: 11 DIV 4 = 2<, >& joins (concatenates) strings: "Ab" & "cd" = "Abcd"
MOD remainder: 11 MOD 4 = 3<=, >=

A common use of MOD: N MOD 2 = 0 tests whether N is even. N MOD 10 gives the last digit and N DIV 10 removes it.

Built-in functions

Your exam paper comes with an insert listing the functions you may use. The common ones:

FunctionReturnsExample
LENGTH(S)Number of characters in SLENGTH("Happy") = 5
LEFT(S, n)The leftmost n charactersLEFT("ABCDEF", 3) = "ABC"
RIGHT(S, n)The rightmost n charactersRIGHT("ABCDEF", 2) = "EF"
MID(S, x, n)n characters starting at position x (the first is 1)MID("ABCDEF", 2, 3) = "BCD"
TO_UPPER(S), TO_LOWER(S)S in upper or lower case (also works on a CHAR)TO_UPPER("pak") = "PAK"
NUM_TO_STR(x)A number converted to a stringNUM_TO_STR(12.5) = "12.5"
STR_TO_NUM(S)A numeric string converted to a numberSTR_TO_NUM("42") = 42
IS_NUM(S)TRUE if S represents a valid numberIS_NUM("12a") = FALSE
ASC(c), CHR(n)The ASCII code of a character, or the character for a codeASC('A') = 65, CHR(66) = 'B'
INT(x)The integer part of x (rounds down for positive numbers)INT(7.8) = 7
RAND(x)A random REAL from 0 up to (not including) xINT(RAND(6)) + 1 gives 1 to 6

Older papers use UCASE and LCASE instead of TO_UPPER and TO_LOWER. Use whichever your paper's insert lists.

Selection

IF Mark >= 50 THEN
    OUTPUT "Pass"
ELSE
    IF Mark >= 40 THEN
        OUTPUT "Resit"
    ELSE
        OUTPUT "Fail"
    ENDIF
ENDIF

CASE OF Choice
    1 : CALL AddRecord()
    2 : CALL DeleteRecord()
    3 TO 5 : OUTPUT "Coming soon"
    OTHERWISE : OUTPUT "Invalid choice"
ENDCASE

Use CASE when one variable is checked against several specific values or ranges; it is neater than many nested IFs.

Iteration

LoopUse it whenRuns
FOR … NEXT (count-controlled)You know in advance how many times to repeatA fixed number of times
WHILE … ENDWHILE (pre-condition)The loop may not need to run at all, such as reading a possibly empty fileZero or more times; the condition is tested before each iteration
REPEAT … UNTIL (post-condition)The loop must run at least once, such as input validationOne or more times; the condition is tested after each iteration
FOR Count ← 10 TO 0 STEP -2        // 10, 8, 6, 4, 2, 0
    OUTPUT Count
NEXT Count

REPEAT                              // validation: always asks at least once
    OUTPUT "Enter a mark from 0 to 100"
    INPUT Mark
UNTIL Mark >= 0 AND Mark <= 100

WHILE Password <> "letmein" AND Attempts < 3
    INPUT Password
    Attempts ← Attempts + 1
ENDWHILE

Procedures and functions

A procedure performs a task. A function performs a task and returns a single value, so it is used inside an expression.

PROCEDURE ShowLine(Symbol : CHAR, Length : INTEGER)
    DECLARE Line : STRING
    DECLARE I : INTEGER
    Line ← ""
    FOR I ← 1 TO Length
        Line ← Line & Symbol
    NEXT I
    OUTPUT Line
ENDPROCEDURE

FUNCTION Area(Width : REAL, Height : REAL) RETURNS REAL
    RETURN Width * Height
ENDFUNCTION

CALL ShowLine('*', 20)               // a procedure is CALLed
Total ← Area(3.5, 2) + Area(1, 1)    // a function is used in an expression

Parameters by value and by reference

BYVAL
A copy of the value is passed. Changes inside the subroutine do not affect the original variable. This is the default.
BYREF
The address (a reference to the original variable) is passed. Changes inside the subroutine change the original.
PROCEDURE Swap(BYREF X : INTEGER, BYREF Y : INTEGER)
    DECLARE Temp : INTEGER
    Temp ← X
    X ← Y
    Y ← Temp
ENDPROCEDURE

Local and global variables

A global variable is declared in the main program and can be used anywhere. A local variable is declared inside a subroutine and exists only while it runs. Prefer local variables: modules are independent, easier to test and reuse, and can't accidentally change data elsewhere.

Why use subroutines?

  • The program is split into manageable, named modules that are easier to understand.
  • Code is written once and called many times, so programs are shorter.
  • Each module can be tested on its own and reused in other programs.
  • Several programmers can work on different modules at the same time.

Exam-style questions

1Paper 2 style
Write a function CountVowels() that takes a string as a parameter and returns the number of vowels (a, e, i, o, u, in upper or lower case) it contains.
[6]
Show mark scheme
FUNCTION CountVowels(ThisString : STRING) RETURNS INTEGER
    DECLARE Count, Index : INTEGER
    DECLARE ThisChar : CHAR
    Count ← 0
    FOR Index ← 1 TO LENGTH(ThisString)
        ThisChar ← TO_LOWER(MID(ThisString, Index, 1))
        IF ThisChar = 'a' OR ThisChar = 'e' OR ThisChar = 'i' OR ThisChar = 'o' OR ThisChar = 'u' THEN
            Count ← Count + 1
        ENDIF
    NEXT Index
    RETURN Count
ENDFUNCTION
  • Function heading with a STRING parameter and RETURNS INTEGER
  • Count declared and initialised to 0
  • Loop from 1 to LENGTH(ThisString)
  • Extract each character with MID
  • Test against all five vowels, handling case
  • Increment the count and return it after the loop
2Paper 2 style
Write a function ValidPassword() that takes a password string as a parameter. It returns TRUE if the password has at least 8 characters, at least one digit and at least one upper-case letter, otherwise FALSE.
[7]
Show mark scheme
FUNCTION ValidPassword(Pwd : STRING) RETURNS BOOLEAN
    DECLARE Index : INTEGER
    DECLARE HasDigit, HasUpper : BOOLEAN
    DECLARE C : CHAR
    IF LENGTH(Pwd) < 8 THEN
        RETURN FALSE
    ENDIF
    HasDigit ← FALSE
    HasUpper ← FALSE
    FOR Index ← 1 TO LENGTH(Pwd)
        C ← MID(Pwd, Index, 1)
        IF C >= '0' AND C <= '9' THEN
            HasDigit ← TRUE
        ENDIF
        IF C >= 'A' AND C <= 'Z' THEN
            HasUpper ← TRUE
        ENDIF
    NEXT Index
    RETURN HasDigit AND HasUpper
ENDFUNCTION
  • Function heading with a parameter and RETURNS BOOLEAN
  • Length check of at least 8
  • Two flags initialised to FALSE
  • Loop through every character
  • Correct digit test (range '0' to '9', or IS_NUM)
  • Correct upper-case test (range 'A' to 'Z', or ASC 65 to 90)
  • Returns TRUE only if all conditions are met, otherwise FALSE
3Paper 2 style
DECLARE N, Result, Digit : INTEGER
N ← 2547
Result ← 0
WHILE N > 0
    Digit ← N MOD 10
    Result ← Result * 10 + Digit
    N ← N DIV 10
ENDWHILE
OUTPUT Result
(a)
Complete a trace table for the algorithm, with columns for N, Digit, Result and OUTPUT.
[4]
(b)
State the purpose of the algorithm.
[1]
Show mark scheme
NDigitResultOUTPUT
25470
25477
25474
25745
0274527452
  • (a) One mark for each correct pair of rows (initial values, then each loop), and the final output of 7452.
  • (b) It reverses the order of the digits of N.
4Paper 2 style
(a)
Explain the difference between passing a parameter by value and by reference.
[2]
(b)
Explain why a REPEAT … UNTIL loop is more suitable than a WHILE loop for validating a value that the user inputs.
[2]
Show mark scheme
  • (a) By value: a copy of the value is passed, so changes in the subroutine don't affect the original variable.
  • (a) By reference: the address of the variable is passed, so changes in the subroutine affect the original variable.
  • (b) The user must enter a value at least once, and a post-condition loop always runs at least once.
  • (b) The condition can only be tested after the value has been input, which is when REPEAT … UNTIL tests it; a WHILE loop would need an extra INPUT before the loop.

Real software is planned, designed, built, tested and then maintained for years. This topic covers the stages of that life cycle, the design diagrams Paper 2 uses, and how to choose test data that catches errors.

The program development life cycle

Analysis
Investigate the problem and the current system; identify the requirements with the client (a requirements specification); use abstraction and decomposition.
Design
Plan the solution: structure charts, algorithms (pseudocode, flowcharts), data structures, interface designs, and the test plan.
Coding
Write the program in a programming language, module by module, with iterative testing along the way.
Testing
Run the program with test data to find and remove errors and check it meets the requirements.
Maintenance
After the program is in use: fix errors that appear, adapt it to new needs, and improve it.

Life cycle models

ModelHow it worksBenefitsDrawbacks
WaterfallEach stage is completed and signed off before the next begins; the flow goes one way, with little going back.Simple to understand and manage; clear milestones and documentation; works well when requirements are fixed and well understood.Little client involvement after analysis; a working program appears only late in the project; changing requirements is costly; errors found late are expensive to fix.
IterativeA simple version is built, then improved in repeated cycles (iterations), each one going through design, coding and testing.A working version is available early; the client gives feedback on each version; problems are found and fixed sooner; easier to adapt to changing requirements.Needs good planning to divide the system; total cost and time are hard to predict; may need more resources.
Rapid Application Development (RAD)Very little up-front planning. Prototypes of modules are developed quickly and in parallel, using reusable components and constant user feedback.Fast delivery; the client is involved throughout, so the result matches their needs; changes are easy to include.Needs skilled developers and constant client commitment; less suitable for large or complex systems; documentation may be poor; the overall design may be weak.

Structure charts

A structure chart shows how a problem is decomposed into modules, arranged as a hierarchy, and the parameters passed between them.

Process Order Get Order Calculate Total Print Receipt ItemsItemsTotalTotalPrinted
An arrow with an open circle is a data couple (data passed as a parameter). An arrow with a filled circle is a flag (a Boolean that signals a condition, such as success). A diamond on a line shows selection; a curved arrow over the lines shows iteration (repeated calls).

State-transition diagrams

A state-transition diagram shows the states a system can be in, the events (inputs) that cause a change of state, and the transitions between them. The arrow coming from nowhere marks the start state.

Locked Unlocked Alarm correct code enteredlock button pressedthird wrong codereset key usedwrong code (1st or 2nd)

Types of error

Syntax error
Breaks the rules of the programming language, such as a misspelt keyword or missing bracket. The translator reports it and the program won't run.
Logic error
The program runs but gives the wrong result because the algorithm is wrong, such as using < instead of <=, or the wrong loop bounds.
Run-time error
Occurs while the program is running and makes it crash, such as dividing by zero, an array index out of range, or opening a file that doesn't exist.

Testing methods

Dry run
Working through an algorithm by hand, recording variable values in a trace table, to check the logic without a computer.
Walkthrough
The programmer explains the code step by step to colleagues, who look for errors.
White-box testing
The tester knows the code and chooses data to test every path through it.
Black-box testing
The code is not looked at; the inputs are tested only against the expected outputs from the specification.
Integration testing
Modules that have been tested separately are combined and tested together, to check they work with each other.
Stub testing
A module that hasn't been written yet is replaced by a simple stub, such as one that just outputs a message or returns a fixed value, so the rest of the program can be tested.
Alpha testing
Carried out in-house by the developers or a test team, before release to users.
Beta testing
A nearly finished version is given to a group of real users outside the company, who report faults.
Acceptance testing
The finished program is tested by the client to check it meets the agreed requirements before it is handed over.

Test data

For an input that must be a whole number from 1 to 100:

TypeMeaningExamplesExpected result
NormalTypical valid data45, 70Accepted
Abnormal (erroneous)Data that should be rejected−5, 250, "ten"Rejected with an error message
ExtremeThe largest and smallest acceptable values1, 100Accepted
BoundaryValues on each side of each limit0 and 1; 100 and 1010 and 101 rejected; 1 and 100 accepted

A test plan lists each test, the purpose, the test data, the expected result, and (after testing) the actual result.

Maintenance

Corrective
Fixing errors (bugs) found after the program has been released.
Adaptive
Changing the program to meet new requirements or to work in a changed environment, such as new laws, a new operating system or new hardware.
Perfective
Improving the program's performance or usability, even though it already works correctly, such as making it faster or improving the interface.

Exam-style questions

1Paper 2 style
A company is developing a new app whose requirements are likely to change. Explain why an iterative model would be more suitable than the waterfall model.
[3]
Show mark scheme
  • Iterative development produces working versions early and improves them in cycles…
  • …so the client can review each version and request changes as requirements change.
  • In waterfall, each stage is completed before the next, so changes after analysis are difficult and costly.
  • Iterative development finds problems earlier, reducing the risk of the final product not meeting needs.

Max 3.

2Paper 2 style

A program asks for an age that must be an integer from 16 to 65 inclusive.

Complete a table giving one example of normal, abnormal, extreme and boundary test data for this input, with the expected result of each.
[4]
Show mark scheme
  • Normal: any integer from 17 to 64, such as 30, accepted.
  • Abnormal: such as −3, 100 or "abc", rejected.
  • Extreme: 16 or 65, accepted.
  • Boundary: 15 or 66 (rejected), with 16 or 65 (accepted).
3Paper 2 style
(a)
Explain what is meant by stub testing.
[2]
(b)
Identify the type of maintenance in each case: (i) the program is changed because the tax rate has changed; (ii) a bug that crashes the program on 29 February is fixed; (iii) a slow search is replaced with a faster one.
[3]
Show mark scheme
  • (a) A module that hasn't been written yet is replaced by a simple placeholder (stub)…
  • (a) …that returns a fixed value or outputs a message, so the rest of the program can be tested.
  • (b)(i) Adaptive
  • (b)(ii) Corrective
  • (b)(iii) Perfective
4Paper 2 style

Refer to the door-lock state-transition diagram above.

(a)
The lock is in the Locked state. A user enters a wrong code, then the correct code. State the final state.
[1]
(b)
Describe the sequence of events that takes the system from Unlocked to Alarm and back to Locked.
[3]
Show mark scheme
  • (a) Unlocked
  • (b) The lock button is pressed, changing the state from Unlocked to Locked.
  • (b) Three wrong codes are entered in a row (the first two keep it Locked; the third changes it to Alarm).
  • (b) The reset key is used, changing the state from Alarm to Locked.
5Paper 2 style
A program crashes with the error "index out of range". Identify the type of error and describe how a programmer could locate it.
[3]
Show mark scheme
  • It is a run-time error.
  • Set a breakpoint just before the array is accessed, or single-step through the loop…
  • …watching the value of the index variable to see when it goes beyond the array bounds (or do a dry run with a trace table).

A Level Computer Science, one topic at a time

Notes for every section of the Cambridge 9618 syllabus tested in Papers 3 and 4, with worked examples, Python code for the practical paper, and exam-style questions with mark schemes.

Paper 3: Advanced Theory

1 hour 30 minutes75 marks25% of A Level

Topics 13 to 20. Written answers on advanced theory: floating point, protocols, Boolean algebra, operating systems, encryption, AI, algorithms and programming paradigms.

Paper 4: Practical

2 hours 30 minutes75 marks25% of A Level

Topics 19 and 20, except low-level and declarative programming. You write and run programs on a computer in Java, Python or Visual Basic .NET.

Papers 1 and 2 count for the other 50% of the full A Level, so keep revising the AS topics too: Paper 3 often builds on them.

Topics

How to revise with these notes

  • Practise the calculations by hand. Floating point, Boolean simplification, K-maps, RPN and Dijkstra all appear as worked problems. The tools on those pages let you check your working.
  • Type the code. For Paper 4, run every Python example yourself and change it. Reading code is not the same as writing it under time pressure.
  • Learn the sequences. The TLS handshake, digital signatures and the stages of compilation are frequently asked as ordered descriptions. Get the order right.
About the questions

The questions here are written in the style of real 9618 papers. They are not copies of official papers. For genuine past papers and mark schemes, use the Cambridge School Support Hub or ask your teacher.

This topic extends AS data representation in three directions: designing your own data types, organising files so records can be found quickly, and storing real numbers in floating-point binary.

User-defined data types

Built-in types (INTEGER, STRING …) cannot describe everything a program needs. A user-defined data type is created by the programmer to match the data in the problem, making programs easier to read and helping the translator catch errors.

Non-composite types

A non-composite type is defined without referring to another data type.

// Enumerated: an ordered list of all possible values
TYPE Season = (Spring, Summer, Autumn, Winter)
DECLARE ThisSeason : Season
ThisSeason ← Autumn
IF ThisSeason > Summer THEN          // values have an order
    OUTPUT "Second half of the year"
ENDIF

// Pointer: holds the memory address of a variable of a given type
TYPE TIntPointer = ^INTEGER
DECLARE MyPointer : TIntPointer
DECLARE Number, Copy : INTEGER
Number ← 42
MyPointer ← @Number                  // @ gives the address of Number
Copy ← MyPointer^                    // ^ dereferences: Copy becomes 42
MyPointer^ ← 7                       // changes Number to 7

Composite types

A composite type is made up of other data types.

Record
A collection of related fields of possibly different types (see topic 10).
Set
An unordered collection of distinct values of the same type, supporting set operations: membership (is an item in the set?), union, intersection and difference.
Class
A blueprint for objects, combining attributes (data) and methods (procedures and functions) that act on them (see topic 20).
TYPE LetterSet = SET OF CHAR
DEFINE Vowels ('A', 'E', 'I', 'O', 'U') : LetterSet

File organisation and access

OrganisationHow records are storedTypical use
SerialOne after another in the order they were added (chronological). New records are appended to the end.Transaction logs, temporary files, data collected for later processing
SequentialIn order of a key field. Adding a record means rewriting the file to keep the order.Master files processed in batches, such as payroll, where most records are read each run
Random (direct)At an address calculated from the key field by a hashing algorithm, so there is no order in the file.Systems that need fast access to individual records, such as airline bookings or stock lookups
Sequential access
Records are read one after another from the start until the required record is found. Used with serial and sequential files. For a sequential file the search can stop early once the key passes the one being looked for.
Direct access
The record's address is calculated (by hashing the key, or by using an index) and the record is read immediately without reading the others. Used with random files, and with sequential files that have an index.

Hashing

A hashing algorithm calculates a storage address from a record's key, for example Address ← Key MOD 7 for a file with 7 slots. A collision happens when two keys give the same address. Two ways to deal with it:

  • Open hashing (linear probing): store the record in the next free slot after the calculated one, wrapping round at the end.
  • Overflow area: store the record in a separate overflow area, searched serially when the record isn't at its home address.

To find a record, calculate the hash, then check that slot; if it holds a different key, check the following slots (or the overflow area) until the record or an empty slot is found.

KeyKey MOD 7Stored at
4533
2322
1734 (3 is taken)
3835 (3 and 4 are taken)
5236 (3, 4 and 5 are taken)

Notice the cluster forming around slot 3. A good hash function spreads keys evenly, and the file should be larger than the number of records so collisions stay rare.

Floating-point representation

A real number is stored as a mantissa and an exponent, both in two's complement:

value = mantissa × 2exponent

The binary point is assumed to sit just after the first (sign) bit of the mantissa. With an 8-bit mantissa the place values are −1, ½, ¼, ⅛, 1⁄16, 1⁄32, 1⁄64, 1⁄128.

Binary floating point to denary

Mantissa 0.1011000½ + ⅛ + 1⁄16 = 0.6875
Exponent 00113
Value0.6875 × 23 = 5.5

Another way: move the binary point right by the exponent. 0.1011000 with the point moved 3 places gives 0101.1000 = 5.5. For a negative exponent, move the point left.

Mantissa 1.0100000−1 + ¼ = −0.75
Exponent 00102
Value−0.75 × 22 = −3

Denary to normalised floating point

Example: −6.5 with an 8-bit mantissa and 4-bit exponent.

  1. Write +6.5 in binary: 110.1
  2. Move the point so the number starts 0.1: 0.1101 × 23. The exponent is 3 = 0011.
  3. Write the positive mantissa in 8 bits: 0.1101000
  4. For a negative number, take the two's complement: flip the bits (1.0010111) and add 1, giving 1.0011000
  5. Check: −1 + ⅛ + 1⁄16 = −0.8125, and −0.8125 × 8 = −6.5 ✓

Normalisation

A normalised positive mantissa starts 0.1; a normalised negative mantissa starts 1.0. In other words, the first two bits differ. To normalise, shift the mantissa left until they differ, and subtract 1 from the exponent for each place shifted.

Not normalised0.0010110 × 25
Shift mantissa left 2 places0.1011000
Exponent 5 − 23 = 0011
Normalised (same value, 5.5)0.1011000 × 23

Why normalise? It gives the maximum precision for the number of mantissa bits, because no bits are wasted on leading 0s (or 1s). It also means each value has exactly one representation.

Precision, range and errors

  • More mantissa bits means greater precision (more significant figures). More exponent bits means a greater range (larger and smaller magnitudes). With a fixed total, increasing one reduces the other.
  • Many denary fractions, such as 0.1, have no exact binary representation; they recur, like ⅓ in denary. The stored value is only an approximation, which causes rounding errors that can build up over many calculations.
  • Overflow happens when a result is too large to represent: the exponent needed is bigger than the largest the exponent bits allow.
  • Underflow happens when a result is too close to zero to represent: the exponent needed is more negative than allowed, so the value becomes 0.

With an 8-bit mantissa and 4-bit exponent, the largest positive value is 0.1111111 × 27 = 127, the most negative is 1.0000000 × 27 = −128, and the smallest positive normalised value is 0.1000000 × 2−8 = 1⁄512.

Exam-style questions

In questions 1 to 3, the mantissa has 8 bits and the exponent has 4 bits, both in two's complement.

1Paper 3 style
(a)
Convert this floating-point number to denary. Mantissa 0.1101000, exponent 0101.
[2]
(b)
Convert this floating-point number to denary. Mantissa 1.0110000, exponent 1111.
[2]
Show mark scheme
  • (a) Mantissa = 0.8125, exponent = 5 (or point moved 5 places: 011010.00)
  • (a) 0.8125 × 32 = 26
  • (b) Mantissa = −1 + ¼ + ⅛ = −0.625, exponent = −1
  • (b) −0.625 × 2−1 = −0.3125
2Paper 3 style
Show how the denary number −13.25 is represented as a normalised floating-point number. Show your working.
[3]
Show mark scheme
  • 13.25 = 1101.01 = 0.110101 × 24
  • Two's complement of 0.1101010 gives the mantissa 1.0010110
  • Exponent 0100

Check: −1 + ⅛ + 1⁄32 + 1⁄64 = −0.828125, × 16 = −13.25.

3Paper 3 style
(a)
The floating-point number with mantissa 1.1110100 and exponent 0011 is not normalised. Normalise it, giving the new mantissa and exponent.
[2]
(b)
Explain why floating-point numbers are normalised.
[2]
(c)
The system is changed to use a 6-bit mantissa and a 6-bit exponent. Explain the effect on the numbers that can be represented.
[2]
Show mark scheme
  • (a) Mantissa 1.0100000 (shifted left 3 places)
  • (a) Exponent 0000 (3 − 3 = 0). Value is −0.75 in both forms.
  • (b) To give the maximum precision for the number of mantissa bits available (no wasted leading bits).
  • (b) So that each number has a unique representation (also makes comparison and arithmetic simpler).
  • (c) Fewer mantissa bits, so less precision.
  • (c) More exponent bits, so a greater range of values.
4Paper 3 style

Records are stored in a random file with 8 slots, numbered 0 to 7. The hashing algorithm is Address ← Key MOD 8. Collisions are handled by storing the record in the next free slot.

(a)
Records with keys 27, 18, 43, 35 and 50 are added in that order. State the slot in which each is stored.
[3]
(b)
Describe how the record with key 50 would be found.
[2]
Show mark scheme
  • (a) 27 → 3; 18 → 2
  • (a) 43 → 4 (3 is taken); 35 → 5 (3 and 4 are taken)
  • (a) 50 → 6 (its hash is 2; slots 2, 3, 4 and 5 are taken)
  • (b) Apply the hash: 50 MOD 8 = 2, and read slot 2.
  • (b) The key doesn't match, so read the following slots in turn until key 50 is found (at slot 6) or an empty slot shows it isn't stored.
5Paper 3 style
(a)
A company's payroll is processed once a month for every employee. Its booking system must find a single customer's booking instantly. State and justify the most suitable file organisation for each.
[4]
(b)
Write pseudocode to declare an enumerated type Direction with the values North, East, South and West, and a variable of that type set to South.
[2]
Show mark scheme
  • (a) Payroll: sequential file…
  • (a) …because every record is processed in order of the key in each run, so sequential access is efficient.
  • (a) Bookings: random (direct access) file…
  • (a) …because the address can be calculated from the key by hashing, so one record is read directly without reading others.
  • (b) TYPE Direction = (North, East, South, West)
  • (b) DECLARE Heading : Direction and Heading ← South

A protocol is a set of rules that devices agree on so they can communicate. This topic covers the TCP/IP protocol suite, the main application protocols, peer-to-peer file sharing with BitTorrent, and the two ways data can travel across a network.

Why protocols are needed

Devices from different manufacturers, running different software, must agree on things like the format of data, how it is addressed, error checking, and how fast it is sent. Protocols set these rules. Splitting the job into layers means each layer deals with one part of the job and only talks to the layers directly above and below; a layer can be changed (say, Wi-Fi replaced by Ethernet) without changing the others.

The TCP/IP protocol suite

Application Transport Internet Link HTTP, FTP, SMTP, POP3, IMAP, DNSdata for the application TCP (or UDP), port numberssplits data into segments, numbered IP addresses and routingpackets addressed and routed Ethernet, Wi-Fi, MAC addressesframes sent over the physical medium
When sending, data passes down the stack and each layer adds its own header. When receiving, it passes up and each layer removes its header.
LayerRole
ApplicationProvides the protocols applications use to exchange data, such as HTTP for web pages and SMTP for email. Decides the format of the data.
TransportTCP splits the data into segments, adds a header with port numbers and a sequence number, and sets up a connection with the destination. It makes delivery reliable: the receiver acknowledges segments, lost ones are resent, and they are reassembled in the correct order. (UDP is faster but gives no guarantee.)
Internet (network)IP adds the source and destination IP addresses to form packets, and routes each packet across networks through routers, hop by hop.
LinkHandles physical transmission over the local network: adds MAC addresses to form frames and converts them to signals on the cable or radio link.

Application protocols

HTTP
HyperText Transfer Protocol. The browser sends requests (such as GET or POST) to a web server, which returns web pages and other resources. HTTPS is HTTP made secure with TLS.
FTP
File Transfer Protocol. Uploads and downloads files between a client and a server, often with a login; supports listing, renaming and deleting files on the server.
SMTP
Simple Mail Transfer Protocol. A push protocol: sends email from the client to the sender's mail server, and between mail servers.
POP3
Post Office Protocol 3. A pull protocol: downloads email from the server to one device, and usually deletes it from the server. Mail is then available offline but not synchronised across devices.
IMAP
Internet Message Access Protocol. A pull protocol that keeps email on the server and synchronises it, so the same mailbox, folders and read status appear on every device.

BitTorrent

BitTorrent is a peer-to-peer protocol for sharing large files without one central server doing all the work.

  1. The file is split into many small, equal-sized pieces, each with a hash so it can be checked.
  2. A small .torrent file holds metadata: the file name and size, the piece hashes, and the address of a tracker.
  3. A user's BitTorrent client contacts the tracker, which keeps a list of the peers currently sharing that file (the swarm).
  4. The client downloads different pieces from many peers at the same time, checks each piece against its hash, and reassembles the file.
  5. As soon as it has a piece, it also uploads that piece to other peers. A seed has the complete file; a leech downloads without uploading much in return.

Benefits: fast downloads for popular files, since there are many sources; no single server is overloaded or a single point of failure. Drawbacks: availability depends on enough seeds being online; it is widely used to share copyrighted material illegally; downloaded files can carry malware.

Circuit switching and packet switching

Circuit switching
A dedicated path (circuit) between sender and receiver is set up before any data is sent. All data follows that path, arrives in order, and the circuit is reserved for the whole communication, then released. Traditional landline telephone calls work this way.
Packet switching
The message is split into packets. Each packet has a header containing the source and destination addresses and a sequence number. Packets travel independently and may take different routes, chosen by routers; they are reassembled in order at the destination. The links are shared with other users' traffic. The internet works this way.
Circuit switchingPacket switching
Dedicated, exclusive path for the whole callNo dedicated path; links are shared
Data arrives in order with a constant delay, good for real-time voice and videoPackets may arrive out of order and with varying delays, so they must be reordered
Bandwidth is wasted when no data is being sentEfficient use of bandwidth
If any link on the circuit fails, communication stopsIf a link fails, packets are rerouted, so it is more robust
Setting up the circuit takes timeNo setup; each packet carries its own address
Harder to intercept, as only one pathPackets travel through many devices; encryption may be needed

The role of a router in packet switching

A router reads the destination IP address in each packet's header, looks up its routing table to choose the best next hop towards that destination (taking into account traffic and faults), and forwards the packet. Routers exchange information so their tables stay up to date, which is how packets can be rerouted around problems.

Exam-style questions

1Paper 3 style
A user sends an email. Describe the role of each layer of the TCP/IP protocol suite in sending the email.
[8]
Show mark scheme

Up to 2 marks per layer.

  • Application: the email client uses SMTP to prepare the message…
  • …and pass it to the transport layer, addressed to the mail server's port.
  • Transport: TCP splits the data into segments and adds a header with port numbers and a sequence number…
  • …and ensures reliable delivery using acknowledgements and retransmission of lost segments.
  • Internet: IP adds the source and destination IP addresses to each packet…
  • …and routes the packets across networks via routers.
  • Link: adds MAC addresses to form frames for the local network…
  • …and transmits them as signals over the physical medium.
2Paper 3 style
Sana reads her email on her phone, tablet and laptop. Explain why IMAP is more suitable for her than POP3.
[3]
Show mark scheme
  • IMAP keeps the emails on the mail server.
  • So the same emails, folders and read/unread status are synchronised and visible on all three devices.
  • POP3 downloads email to one device and usually deletes it from the server, so it would not appear on her other devices.
3Paper 3 style
Describe how the BitTorrent protocol allows a large file to be shared between many users.
[5]
Show mark scheme
  • The file is divided into small pieces.
  • A torrent file containing metadata and the address of a tracker is downloaded.
  • The client contacts the tracker, which identifies the peers in the swarm that have pieces of the file.
  • Pieces are downloaded from several peers simultaneously and reassembled.
  • Each piece is checked using its hash value.
  • Peers upload pieces they already have to other peers while downloading; seeds hold the complete file.

Max 5.

4Paper 3 style
(a)
Describe how a message is sent using packet switching.
[4]
(b)
Give one benefit of circuit switching over packet switching for a live video call.
[1]
Show mark scheme
  • (a) The message is split into packets.
  • (a) Each packet has a header with the source and destination addresses and a sequence number.
  • (a) Packets travel independently and may take different routes; routers decide the next hop for each packet.
  • (a) At the destination the packets are reordered using their sequence numbers; missing packets are requested again.
  • (b) A dedicated circuit means data arrives in order with a constant, low delay, so the video and sound don't break up.

How processor design affects speed, how many processors can share a job, how one machine can pretend to be another, and the algebra used to simplify and build logic circuits, including the adders and flip-flops inside every CPU.

RISC and CISC

RISC (Reduced Instruction Set Computer)CISC (Complex Instruction Set Computer)
Fewer, simpler instructionsMany instructions, some very complex
Instructions have a fixed length and few formatsInstructions vary in length and format
Most instructions take one clock cycleInstructions can take many clock cycles
Few addressing modesMany addressing modes
Many general-purpose registers; only load and store instructions access memoryFewer registers; many instructions can work on memory directly
Hard-wired control unitUsually a microprogrammed control unit
Simple uniform instructions make pipelining easy and efficientPipelining is harder because instructions vary
Programs need more instructions, so compilers do more work; uses less power (phones, tablets)Shorter programs that need less memory; easier to write in assembly (desktop PCs)

Pipelining

Pipelining is instruction-level parallelism: the fetch-execute cycle is split into stages, and different instructions are at different stages at the same time, like an assembly line. A common five-stage pipeline is: Instruction Fetch (IF), Instruction Decode (ID), Operand Fetch (OF), Instruction Execute (IE), Write Back (WB).

StageCycle 1234567
IF1234567
ID123456
OF12345
IE1234
WB123

Without pipelining, 4 instructions take 4 × 5 = 20 cycles. With a 5-stage pipeline they take 5 + 3 = 8 cycles: once the pipeline is full, one instruction completes every cycle.

Interrupts in a pipelined processor

When an interrupt occurs, several instructions are partly processed. Either the pipeline is flushed (the partly processed instructions are discarded, except the one in its final stage, which completes) and the normal interrupt routine runs, then the discarded instructions are fetched again later; or the processor keeps a separate program counter for each stage, so the state of every instruction in the pipeline can be saved and restored.

Parallel processing

Flynn's taxonomy classifies computer architectures by the number of instruction streams and data streams.

TypeMeaningExample
SISDSingle Instruction, Single Data: one processor executes one instruction on one item of data at a timeEarly single-core personal computers
SIMDSingle Instruction, Multiple Data: the same instruction is applied to many data items at onceGraphics processors (changing the brightness of every pixel), array processors
MISDMultiple Instruction, Single Data: several processors apply different instructions to the same dataRare; fault-tolerant systems such as flight control computers that cross-check results
MIMDMultiple Instruction, Multiple Data: several processors each execute different instructions on different dataMulti-core processors, supercomputers, clusters

Massively parallel computers

A massively parallel computer has a very large number of processors (thousands or more), each usually with its own memory, linked by a high-speed interconnection network. A big problem is split into many parts that are processed simultaneously, with the processors communicating to combine results. Used for weather forecasting, scientific simulation and training AI models. The software must be specially written so the problem can be split up; some tasks cannot be parallelised.

Virtual machines

A virtual machine (VM) is software that emulates a complete computer system. A guest operating system runs inside the VM, on top of the host computer and its OS, managed by software called a hypervisor. The Java Virtual Machine is a process VM: it emulates a machine that runs Java bytecode on any host.

  • Benefits: several different operating systems can run on one physical computer; software can be tested on different platforms without buying hardware; each VM is isolated, so a crash or malware in the guest doesn't affect the host; old (legacy) software can run on new hardware; servers can be consolidated, saving cost and energy.
  • Drawbacks: the guest runs more slowly than it would on real hardware, because of the extra layer of emulation; it needs a powerful host with lots of memory; it is complex to set up and manage; if the host fails, every VM on it fails.

Boolean algebra

A bar over a term means NOT. A dot means AND and a plus means OR, so A.B + C means (A AND NOT B) OR C.

LawAND formOR form
IdentityA.1 = AA + 0 = A
Null (annulment)A.0 = 0A + 1 = 1
IdempotentA.A = AA + A = A
InverseA.A = 0A + A = 1
Double complementA = A
CommutativeA.B = B.AA + B = B + A
Associative(A.B).C = A.(B.C)(A + B) + C = A + (B + C)
DistributiveA.(B + C) = A.B + A.CA + B.C = (A + B).(A + C)
AbsorptionA.(A + B) = AA + A.B = A
RedundancyA.(A + B) = A.BA + A.B = A + B
De Morgan'sA.B = A + BA + B = A.B

De Morgan's laws in words: to break a bar, change the operator under it (AND becomes OR, OR becomes AND) and put a bar over each term.

Worked simplification

X = A.B.C + A.B.C + A.B.C
= A.B.(C + C) + A.B.CDistributive: factor out A.B
= A.B.1 + A.B.C = A.B + A.B.CInverse, then identity
= B.(A + A.C)Factor out B
= B.(A + C) = A.B + B.CRedundancy law

Try typing (A AND B) OR (B AND C) into the builder: the output column is identical, which proves the simplification.

Karnaugh maps

A K-map is a grid version of a truth table, laid out so that neighbouring cells differ in exactly one variable (the column labels use Gray code: 00, 01, 11, 10). Grouping adjacent 1s removes the variable that changes within the group.

Rules for grouping

  • Groups contain only 1s, and must be rectangles of 1, 2, 4, 8 or 16 cells.
  • Make each group as large as possible, and use as few groups as possible.
  • Groups may overlap, and may wrap around the edges (the left and right edges are adjacent, as are the top and bottom).
  • For each group, keep only the variables that stay the same throughout it.

Example: X is 1 for the inputs ABC = 001, 011, 101, 110, 111.

A \ BC00011110
00110
10111

The group of four (outlined in the accent colour) has C = 1 throughout, while A and B change, so it gives C. The pair (outlined in red) has A = 1 and B = 1, while C changes, so it gives A.B. The result is X = C + A.B.

Benefits of K-maps: simplification is quicker and less error-prone than algebra, and they guarantee the minimum sum-of-products expression when grouped correctly.

Adders

Half adder

Adds two bits, A and B, giving a sum bit S and a carry bit C: S = A XOR B, C = A AND B.

AB SC
ABSC
0000
0110
1010
1101

Full adder

Adds three bits: A, B and a carry-in Cin from the previous column. It is built from two half adders and an OR gate: the first half adder adds A and B; the second adds that sum to Cin; the two carry outputs are ORed to give Cout. Chaining full adders adds multi-bit numbers.

S = A XOR B XOR Cin   Cout = A.B + Cin.(A XOR B)

ABCinSCout
00000
00110
01010
01101
10010
10101
11001
11111

Flip-flops

A flip-flop is a circuit with two stable states, so it can store one bit. Its output depends on its inputs and its previous state (it is sequential, not combinational). Flip-flops are the storage elements in registers and in SRAM.

SR flip-flop

Built from two cross-coupled NOR gates (or NAND gates): each gate's output feeds back into the other's input.

RS QQ
SRQEffect
00unchangedStores (remembers) the previous state
101Set
010Reset
11invalidBoth Q and Q become 0, and the state when inputs return to 0 is unpredictable

JK flip-flop

A JK flip-flop adds a clock input, so the state only changes on a clock pulse (synchronised with the rest of the circuit), and it removes the invalid state: when J = K = 1, the output toggles.

JKQ after the clock pulse
00unchanged
101 (set)
010 (reset)
11toggles (opposite of previous Q)

Exam-style questions

1Paper 3 style
Describe four differences between RISC and CISC processors.
[4]
Show mark scheme
  • RISC has fewer, simpler instructions; CISC has many complex instructions.
  • RISC instructions are a fixed length; CISC instructions vary in length.
  • RISC instructions mostly take one clock cycle; CISC instructions take several.
  • RISC has fewer addressing modes; CISC has many.
  • RISC has more general-purpose registers; CISC has fewer.
  • RISC is easier to pipeline; CISC is harder.
  • RISC is hard-wired; CISC is often microprogrammed.

Max 4. Each mark needs both sides of the comparison.

2Paper 3 style
(a)
Explain how pipelining improves the performance of a processor.
[2]
(b)
Explain one way an interrupt can be handled in a pipelined processor.
[2]
Show mark scheme
  • (a) The fetch-execute cycle is split into stages, and different instructions are processed at different stages simultaneously.
  • (a) Once the pipeline is full, one instruction is completed every clock cycle, increasing throughput.
  • (b) The pipeline is flushed: partly processed instructions are discarded (except the one in the final stage), and the interrupt service routine runs. The discarded instructions are refetched afterwards.
  • (b) Alternatively, a separate program counter is kept for each stage, so all partly processed instructions can be saved and resumed.
3Paper 3 style
(a)
A software company tests its programs on several operating systems. Explain two benefits and one drawback of using virtual machines for this.
[3]
(b)
Describe the characteristics of a massively parallel computer.
[3]
Show mark scheme
  • (a) Benefit: several operating systems can run on one physical computer, saving hardware costs.
  • (a) Benefit: each VM is isolated, so a crash or virus during testing doesn't affect the host or other VMs.
  • (a) Benefit: VMs can be reset quickly to a saved state for repeat testing.
  • (a) Drawback: programs run more slowly in a VM than on real hardware, so performance tests may not be accurate.
  • (b) A very large number of processors…
  • (b) …working simultaneously on different parts of the same problem (each with its own memory)…
  • (b) …linked by a high-speed interconnection network so they can communicate.
4Paper 3 style
(a)
Simplify A.B + A.B + A.B using Boolean algebra. Show your working.
[3]
(b)
Use De Morgan's laws to simplify A + B.
[2]
Show mark scheme
  • (a) Use A.B twice (idempotent): (A.B + A.B) + (A.B + A.B)
  • (a) = B.(A + A) + A.(B + B) = B.1 + A.1
  • (a) = A + B
  • (b) A.B (break the bar, change OR to AND)
  • (b) = A.B
5Paper 3 style

The K-map shows a logic function X of four inputs A, B, C and D.

AB \ CD00011110
001001
010110
110111
101001
Identify the groups of 1s and write the simplified sum-of-products expression for X.
[4]
Show mark scheme
  • The four corner cells form a group (wrapping both ways): B.D
  • The central square (rows 01 and 11, columns 01 and 11): B.D
  • The remaining 1 at AB = 11, CD = 10 is paired with its neighbour: A.B.C (with the cell to its left) or A.C.D (with the cell below)
  • X = B.D + B.D + A.B.C (or + A.C.D)
6Paper 3 style
(a)
Explain the problem with an SR flip-flop when S = 1 and R = 1.
[2]
(b)
Explain how a JK flip-flop overcomes this problem, and one other advantage it has.
[2]
Show mark scheme
  • (a) Both outputs Q and Q become 0, which is invalid because they should be complements.
  • (a) When S and R return to 0, the final state is unpredictable.
  • (b) When J = K = 1, the output toggles (changes to the opposite of its current value), so there is no invalid state.
  • (b) It has a clock input, so changes are synchronised with the clock.

At A Level you need to know how the operating system shares the processor and memory between many processes, and what happens inside a compiler, including how grammars are defined and how expressions are evaluated with Reverse Polish Notation.

What the OS is for

The operating system aims to make the best use of the computer's resources (processor, memory, storage, I/O devices) and to provide a user interface that hides the complexity of the hardware, through a GUI or command line and through system calls (APIs) that programs use instead of controlling hardware directly.

The kernel is the core of the OS. It stays in memory and manages processes, memory, interrupts and device drivers.

Process management

A process is a program that has started executing. Multitasking means several processes appear to run at the same time: the scheduler switches the processor between them so quickly that each makes progress.

Ready Running Blocked newscheduler dispatches ittime slice ends or pre-empted waits for I/O or an eventI/O or event completesends
Running
The process is being executed by the processor. Only one process per core can be running.
Ready
The process could run and is waiting in the ready queue for processor time.
Blocked
The process is waiting for an event, such as input/output to finish. It can't use the processor even if it is free.

A blocked process can't go straight to running: when its event completes it goes back to ready and must wait to be scheduled. A ready process can't become blocked, because only a running process can request I/O.

Scheduling

The low-level scheduler decides which ready process gets the processor next. A pre-emptive algorithm can stop a running process to give the processor to another; a non-pre-emptive one lets each process run until it finishes or blocks.

AlgorithmHow it worksPre-emptive?
First come, first served (FCFS)Processes run in the order they arrive. Simple, but a long job holds up all the short ones behind it.No
Shortest job first (SJF)The process with the shortest burst time runs next. Gives the lowest average waiting time, but needs burst times to be known, and long jobs may wait indefinitely (starvation).No
Shortest remaining time (SRT)Like SJF, but a newly arriving process with a shorter remaining time pre-empts the running one.Yes
Round robin (RR)Each process gets a fixed time slice (quantum) in turn. If it hasn't finished, it goes to the back of the ready queue. Fair and responsive; too short a quantum wastes time on switching.Yes

Worked example: P1 needs 5 time units, P2 needs 3 and P3 needs 1. All arrive at time 0, in that order.

Time012345678Average wait
FCFSP1P1P1P1P1P2P2P2P3(0 + 5 + 8) ÷ 3 = 4.33
SJFP3P2P2P2P1P1P1P1P1(4 + 1 + 0) ÷ 3 = 1.67
RR, quantum 2P1P1P2P2P3P1P1P2P1(4 + 5 + 4) ÷ 3 = 4.33

Waiting time = finish time − burst time (since all arrive at 0). In RR, P3 finishes at 5, P2 at 8 and P1 at 9.

Interrupt handling

When an interrupt arrives, the OS saves the state of the current process (its registers, in its process control block), identifies the interrupt source, runs the correct interrupt service routine, then the scheduler decides which process runs next, which may not be the one that was interrupted.

Memory management

Paging
Logical memory (the program) is divided into fixed-size pages, and physical memory into frames of the same size. Pages can be placed in any free frames, not necessarily together. A page table maps each page number to its frame. Space at the end of the last page may be wasted (internal fragmentation).
Segmentation
The program is divided into variable-size segments that match its logical parts (such as a procedure or a block of data). A segment table holds each segment's base address and length. Free memory can be left in gaps too small to use (external fragmentation).
Virtual memory
Secondary storage is used as if it were extra RAM. Only the pages currently needed are kept in RAM; others are held on disk and swapped in when required. This lets programs larger than RAM run, and lets more programs be open at once.
Disk thrashing
When RAM is too full, pages are swapped in and out so often that the computer spends more time moving pages than executing instructions, and performance drops sharply. The point where this starts is the thrash point.
Page replacement
When a new page is needed and RAM is full, the OS chooses a page to swap out, for example the one that has been in memory longest (first in, first out) or the one used least recently (LRU).

How an interpreter runs a program

An interpreter doesn't produce a translated version. It reads each statement of the source code, analyses it (checks the syntax and works out what it means), then executes it immediately by calling its own pre-written, already-compiled routines that carry out that kind of statement. It then moves on to the next statement, so a statement inside a loop is analysed again each time.

The stages of compilation

1. Lexical analysis
Removes whitespace and comments. Splits the source code into tokens (keywords, identifiers, operators, literals). Keywords are looked up in a keyword table; identifiers are added to the symbol table with information such as their data type and address.
2. Syntax analysis
Parses the token stream, checking it against the grammar rules of the language. Builds a parse tree and reports syntax errors.
3. Code generation
Produces object code (machine code or an intermediate code) from the parse tree.
4. Optimisation
Improves the object code so it runs faster or uses less memory, without changing what it does: removing redundant or unreachable code, moving calculations that don't change out of loops, replacing a constant expression such as 60 * 60 with its value.

Grammars: BNF and syntax diagrams

Backus-Naur Form defines the rules (syntax) of a language. ::= means "is defined as", | means "or", and items in angle brackets are non-terminals (defined by other rules). Recursion lets a rule repeat.

<digit>      ::= 0|1|2|3|4|5|6|7|8|9
<letter>     ::= A|B|C| … |Z
<identifier> ::= <letter> | <identifier><letter> | <identifier><digit>

So an identifier is a letter followed by any number of letters and digits: A, X2 and TOTAL9 are valid; 9X is not. The same rule as a syntax diagram:

identifier letter letter digit

Reverse Polish Notation

In Reverse Polish Notation (RPN) each operator comes after its operands: a + b becomes a b +. RPN needs no brackets and no precedence rules, so a computer can evaluate it in one left-to-right pass with a stack. Compilers convert expressions to RPN for this reason.

  • To evaluate RPN: read tokens left to right. Push each operand onto the stack. For an operator, pop the top two values, apply the operator (the first popped is the right-hand operand), and push the result. At the end, the stack holds the answer.
  • Infix to RPN: (a + b) * (c − d) becomes a b + c d − *. Draw an expression tree and read it in post-order (left, right, root), or use the converter below.

Exam-style questions

1Paper 3 style
(a)
Explain why a process can move from the running state to the ready state.
[2]
(b)
Explain why a process cannot move directly from the blocked state to the running state.
[2]
Show mark scheme
  • (a) Its time slice has ended (round robin)…
  • (a) …or a higher-priority process (or interrupt) needs the processor, so it is pre-empted.
  • (b) When the event it is waiting for completes, the process becomes ready and joins the ready queue…
  • (b) …because the processor may be in use by another process, and only the scheduler decides which ready process runs next.
2Paper 3 style

Three processes arrive at time 0 in the order J1, J2, J3. Their burst times are 4, 6 and 2 units.

(a)
Using round robin with a time quantum of 2 units, state the time at which each process finishes.
[3]
(b)
State which scheduling algorithm would give the lowest average waiting time for these processes, and the order they would run in.
[2]
Show mark scheme

Order: J1 0–2, J2 2–4, J3 4–6 (finished), J1 6–8 (finished), J2 8–10, J2 10–12 (finished).

  • (a) J3 finishes at 6
  • (a) J1 finishes at 8
  • (a) J2 finishes at 12
  • (b) Shortest job first
  • (b) J3, J1, J2
3Paper 3 style
(a)
Describe two differences between paging and segmentation.
[2]
(b)
Explain how virtual memory is used, and how it can lead to disk thrashing.
[4]
Show mark scheme
  • (a) Pages are a fixed size; segments vary in size.
  • (a) Pages are a physical division of memory; segments are logical divisions matching parts of the program.
  • (a) Paging uses a page table of page and frame numbers; segmentation uses a segment table with base addresses and lengths.
  • (b) Secondary storage is used as an extension of RAM when RAM is full.
  • (b) Pages not currently needed are moved out to disk, and swapped back into RAM when they are required.
  • (b) If too many pages are needed, pages are swapped in and out continually…
  • (b) …so the processor spends more time swapping pages than executing instructions (thrashing).

(a) max 2, (b) max 4.

4Paper 3 style
(a)
Describe what happens during the lexical analysis stage of compilation.
[3]
(b)
Explain the purpose of code optimisation, giving an example.
[2]
Show mark scheme
  • (a) Whitespace and comments are removed.
  • (a) The code is split into tokens.
  • (a) Keywords are checked against a keyword table, and identifiers are entered into a symbol table.
  • (a) Some errors, such as an invalid identifier, are reported.
  • (b) To make the object code run faster or use less memory, without changing its result.
  • (b) For example: removing code that can never be executed; moving a calculation whose value doesn't change out of a loop.

(a) max 3.

5Paper 3 style
<digit>  ::= 0|1|2|3|4|5|6|7|8|9
<letter> ::= A|B|C|D
<code>   ::= <letter><digit> | <letter><code>
(a)
State whether each of these is a valid <code>: A1, AB2, 1A, ABC, D45.
[3]
(b)
Write a BNF rule for <pin>, which is exactly three digits.
[1]
Show mark scheme
  • (a) A1 valid; AB2 valid
  • (a) 1A invalid (must start with a letter); ABC invalid (must end with a digit)
  • (a) D45 invalid (only one digit is allowed, at the end)
  • (b) <pin> ::= <digit><digit><digit>
6Paper 3 style
(a)
Convert the infix expression (5 + 3) * 2 − 8 / 4 to Reverse Polish Notation.
[2]
(b)
Show how a stack is used to evaluate your RPN expression. Show the contents of the stack after each operator is applied.
[4]
(c)
Convert the RPN expression a b c * + d − to infix.
[1]
Show mark scheme
  • (a) 5 3 + 2 * 8 4 / − (one mark for 5 3 + 2 *, one for 8 4 / −)
  • (b) Push 5, push 3; + pops 3 and 5, pushes 8. Stack: 8
  • (b) Push 2; * pops 2 and 8, pushes 16. Stack: 16
  • (b) Push 8, push 4; / pops 4 and 8, pushes 2. Stack: 16, 2
  • (b) − pops 2 and 16, pushes 14. Result 14
  • (c) a + b * c − d (brackets such as (a + (b * c)) − d also accepted)

Check (a) and (b) with the converter above.

Encryption keeps data confidential, and the same key mathematics also proves who sent a message and that it hasn't been changed. Learn the purpose of each key, then the TLS handshake and the digital signature process in order.

Encryption terms

Plaintext
The original, readable data.
Ciphertext
The encrypted data, which can't be understood without the key.
Encryption algorithm
The method (cipher) used with a key to turn plaintext into ciphertext, and back.
Key
A value used by the algorithm. Longer keys mean far more possible keys, so a brute-force attack takes much longer.

Encryption does not stop data being intercepted; it stops intercepted data being understood.

Symmetric and asymmetric encryption

SymmetricAsymmetric (public key)
The same secret key is used to encrypt and decrypt.A matching key pair: a public key anyone may know, and a private key kept secret by its owner. Data encrypted with one key can only be decrypted with the other.
Fast, so it suits large amounts of data.Much slower, so it is usually used for small items, such as exchanging a symmetric key or signing a hash.
Problem: the key must be shared securely before use (key distribution). If it is intercepted, all messages can be read.Solves key distribution: the public key can be sent openly.

Which key does what?

  • For confidentiality: the sender encrypts with the recipient's public key. Only the recipient's private key can decrypt it, so only the intended recipient can read the message.
  • For authentication (signatures): the sender encrypts with their own private key. Anyone can decrypt with the sender's public key, which proves it came from the owner of the private key.

Quantum cryptography

Quantum cryptography uses the properties of photons (particles of light) to exchange an encryption key securely, a process called quantum key distribution. Each bit is sent as a photon with a particular polarisation. Measuring a photon changes its state, so if an eavesdropper intercepts the key, errors appear and both parties know the key has been compromised.

  • Benefits: eavesdropping can always be detected; keys are effectively unbreakable by computation; very long keys can be exchanged; it remains secure against future quantum computers.
  • Drawbacks: needs expensive specialist hardware and dedicated fibre-optic links; the distance a key can be sent is limited because photons are lost or their polarisation changes in the cable; the rate of key exchange is relatively low.

SSL and TLS

TLS (Transport Layer Security), the successor to SSL, provides secure communication between a client and a server. It gives encryption (privacy), authentication (the server is who it claims to be) and data integrity (data hasn't been altered). TLS is made of two layers: the handshake protocol, which sets up the secure session, and the record protocol, which encrypts the data sent during it. It is used in HTTPS, email, VoIP and online banking.

The TLS handshake

  1. The client (browser) sends a message to the server requesting a secure connection, listing the TLS versions and encryption algorithms (cipher suites) it supports.
  2. The server replies with the version and cipher suite it has chosen, and sends its digital certificate, which contains its public key.
  3. The client checks that the certificate is valid and was signed by a trusted Certificate Authority.
  4. The client and server establish a shared session key: for example, the client generates one, encrypts it with the server's public key and sends it; only the server can decrypt it with its private key.
  5. Both sides now use the symmetric session key to encrypt all data for the rest of the session (the record protocol). The session key is discarded when the session ends.

Digital certificates

A digital certificate is an electronic document, issued by a trusted Certificate Authority (CA), that links a public key to the identity of its owner. It lets you trust that a public key really belongs to the organisation it claims to.

A certificate contains: the owner's name or organisation, the owner's public key, the name of the issuing CA, a serial number, the dates it is valid from and to, the algorithms used, and the CA's own digital signature.

How one is obtained: the organisation sends its public key and proof of identity to a CA; the CA checks the identity; the CA creates the certificate and signs it with the CA's private key. Browsers already hold CA public keys, so they can verify the CA's signature on any certificate.

Digital signatures

A digital signature proves who sent a message (authentication), that it wasn't altered (integrity), and that the sender can't deny sending it (non-repudiation). The message itself is not encrypted by this process.

The senderThe receiver
1. Puts the message through a hashing algorithm to produce a message digest.4. Decrypts the signature using the sender's public key (from their certificate), recovering the original digest.
2. Encrypts the digest with the sender's private key. This is the digital signature.5. Hashes the received message using the same hashing algorithm, producing a new digest.
3. Sends the message together with the signature (and usually the sender's certificate).6. Compares the two digests. If they match, the message came from the sender and wasn't changed in transit.
Exam tipThe most common mistake is mixing up the keys. A signature is made with the sender's private key and checked with the sender's public key. For a confidential message, encrypt with the recipient's public key.

Exam-style questions

1Paper 3 style
(a)
Explain the main problem with symmetric encryption.
[2]
(b)
Explain how asymmetric encryption ensures that only the intended recipient can read a message.
[3]
Show mark scheme
  • (a) The same key is used to encrypt and decrypt, so the key must be shared with the recipient.
  • (a) If the key is intercepted while being shared, anyone with it can decrypt the messages.
  • (b) The recipient has a key pair: a public key and a private key.
  • (b) The sender encrypts the message using the recipient's public key.
  • (b) Only the recipient's private key, which only they have, can decrypt the message.
2Paper 3 style
Describe how a digital signature is produced by the sender and checked by the receiver.
[6]
Show mark scheme
  • The sender hashes the message to produce a message digest.
  • The digest is encrypted with the sender's private key to form the signature.
  • The message and signature are sent to the receiver.
  • The receiver decrypts the signature with the sender's public key to get the original digest.
  • The receiver hashes the received message with the same algorithm.
  • The two digests are compared: if they match, the message is authentic and unaltered.
3Paper 3 style
(a)
State three items of data contained in a digital certificate.
[3]
(b)
Describe the steps of the TLS handshake when a browser connects to a secure website.
[5]
Show mark scheme
  • (a) Any three: owner's name or organisation; owner's public key; name of the Certificate Authority; serial number; validity (start and expiry) dates; the CA's digital signature; algorithm used.
  • (b) The browser requests a secure connection, sending the TLS versions and cipher suites it supports.
  • (b) The server responds with its chosen cipher suite and its digital certificate (including its public key).
  • (b) The browser verifies the certificate using the CA's public key.
  • (b) A session key is generated, encrypted with the server's public key and sent to the server…
  • (b) …which decrypts it with its private key.
  • (b) Both then use the symmetric session key to encrypt data for the session.

(b) max 5.

4Paper 3 style
Give one benefit and one drawback of quantum cryptography.
[2]
Show mark scheme
  • Benefit: any eavesdropping on the key exchange changes the photons' state, so it is detected (or: keys are virtually unbreakable; long keys can be exchanged).
  • Drawback: needs expensive dedicated hardware and fibre (or: limited transmission distance; photon polarisation can change in transit, causing errors).

This topic covers two halves of AI: searching a graph for the best route with Dijkstra's algorithm and A*, and machine learning, where a system improves by learning from data rather than following hand-written rules.

Graphs in AI

A graph is a set of nodes (vertices) connected by edges. Edges may be weighted (a cost, distance or time) and may be directed (one way). Graphs let AI model problems as states and moves: places on a map, positions in a game, or concepts in a knowledge network. Finding the best solution then becomes finding the lowest-cost path through the graph.

Dijkstra's algorithm

Dijkstra's algorithm finds the shortest path from a start node to every other node in a graph with non-negative weights.

  1. Give the start node a distance of 0 and every other node ∞. Mark all nodes unvisited.
  2. Choose the unvisited node with the smallest distance and mark it visited. Its distance is now final.
  3. For each unvisited neighbour, calculate the distance through the current node (current distance + edge weight). If that is smaller than the neighbour's recorded distance, update it and record the current node as its previous node.
  4. Repeat from step 2 until every node has been visited (or the destination has been visited).
  5. Trace back through the previous nodes from the destination to find the route.

The A* algorithm

A* finds the shortest path to one goal more efficiently by also using a heuristic: an estimate of the remaining distance to the goal, such as the straight-line distance on a map. For each node it calculates:

f(n) = g(n) + h(n)

where g(n) is the actual cost from the start to n, and h(n) is the heuristic estimate from n to the goal. A* always expands the open node with the lowest f, so it heads towards the goal and usually explores far fewer nodes than Dijkstra. If the heuristic never overestimates the true distance, A* is guaranteed to find the shortest path.

Worked example: the same graph as above, from A to F, with heuristic values h(A) = 9, h(B) = 7, h(C) = 8, h(D) = 5, h(E) = 3, h(F) = 0.

ExpandOpen nodes after expanding: g + h = f
AB: 4 + 7 = 11   C: 2 + 8 = 10
C (f = 10)B: 3 + 7 = 10 (improved, via C)   D: 10 + 5 = 15   E: 12 + 3 = 15
B (f = 10)D: 8 + 5 = 13 (improved, via B)   E: 15
D (f = 13)E: 10 + 3 = 13 (improved, via D)   F: 14 + 0 = 14
E (f = 13)F: 13 + 0 = 13 (improved, via E)
F (f = 13)Goal reached: A → C → B → D → E → F, cost 13

Machine learning

Machine learning is a branch of AI in which a system learns from data and improves its performance at a task without being explicitly programmed with rules for every case.

TypeHow it learnsExample
Supervised learningTrained on labelled data: each input comes with the correct output. It learns to map inputs to outputs, then predicts outputs for new inputs. Used for classification (which category?) and regression (what value?).Spam filtering trained on emails marked spam or not spam
Unsupervised learningGiven unlabelled data and finds patterns or groupings (clusters) in it by itself.Grouping customers with similar buying habits
Reinforcement learningAn agent takes actions in an environment and receives rewards or penalties. By trial and error it learns the actions (policy) that maximise its total reward.A program learning to play a game, a robot learning to walk

Artificial neural networks

Input layerHidden layerOutput layer

An artificial neural network (ANN) is loosely modelled on the brain. It has an input layer, one or more hidden layers and an output layer of nodes (artificial neurons). Each connection has a weight. A node multiplies each input by its weight, adds them up, and passes the total through an activation function to produce its output. Learning means adjusting the weights so the network's outputs become correct. ANNs have driven recent progress in machine learning because they can learn very complex, non-linear patterns from examples, rather than needing a programmer to write the rules.

Deep learning

Deep learning uses neural networks with many hidden layers. Each layer learns more abstract features: in an image, edges, then shapes, then whole objects. It can work on raw data (pixels, sound) without people choosing the features. It needs very large amounts of training data and processing power (GPUs), and is used for image recognition, speech recognition, translation and language models.

Back propagation of errors

  1. Training data is fed forward through the network and the output is compared with the expected (correct) output to calculate the error.
  2. The error is sent backwards through the network, layer by layer, working out how much each weight contributed to it.
  3. Each weight is adjusted slightly to reduce the error (gradient descent).
  4. This is repeated over many training examples and many rounds (epochs) until the error is acceptably small.

Regression

Regression is a supervised method that predicts a continuous numeric value by finding the relationship between input variables and the output, for example fitting a line of best fit to predict a house's price from its floor area. The model is adjusted to minimise the difference between its predictions and the real values in the training data.

Exam-style questions

1Paper 3 style
3627382 SPQRT
(a)
Use Dijkstra's algorithm to find the shortest path from S to T. Show the final distance to each node.
[4]
(b)
Explain how the A* algorithm differs from Dijkstra's algorithm.
[2]
Show mark scheme
NodeSPQRT
Distance035810
Previous–SPQR
  • (a) P = 3 via S; Q updated from 6 to 5 via P
  • (a) R updated from 10 (via P) to 8 via Q
  • (a) T updated from 13 (via Q) to 10 via R
  • (a) Path S → P → Q → R → T, total 10
  • (b) A* uses a heuristic: an estimate of the distance from each node to the goal…
  • (b) …and expands the node with the lowest f = g + h, so it searches towards the goal and usually visits fewer nodes.
2Paper 3 style
(a)
Explain the difference between supervised and unsupervised learning, giving an example of each.
[4]
(b)
Describe how reinforcement learning works.
[3]
Show mark scheme
  • (a) Supervised learning uses labelled training data, where the correct output is known for each input.
  • (a) Example: classifying emails as spam using emails already labelled spam/not spam (or predicting prices, diagnosing from labelled scans).
  • (a) Unsupervised learning uses unlabelled data and finds patterns or clusters itself.
  • (a) Example: grouping customers by buying behaviour (or detecting unusual transactions).
  • (b) An agent interacts with an environment by taking actions.
  • (b) It receives a reward for good actions and a penalty for bad ones.
  • (b) By trial and error it learns which actions maximise its total reward over time.
3Paper 3 style
(a)
Describe how back propagation is used to train an artificial neural network.
[4]
(b)
Explain why deep learning is used for tasks such as image recognition.
[2]
Show mark scheme
  • (a) Training data is input and passed forward through the network to produce an output.
  • (a) The output is compared with the expected output to find the error.
  • (a) The error is passed backwards through the network, layer by layer…
  • (a) …and the weights are adjusted to reduce the error.
  • (a) The process is repeated many times until the error is small enough.
  • (b) Deep networks have many hidden layers that learn features automatically, from simple (edges) to complex (objects)…
  • (b) …so they can handle large amounts of complex, unstructured data such as pixels, where hand-written rules would be impossible.

(a) max 4.

The standard searching and sorting algorithms, how to implement the abstract data types, how to compare algorithms with Big O notation, and recursion. Paper 4 expects you to code all of this, so the examples are in pseudocode and Python.

Searching

Linear search

Checks each item in turn. Works on unsorted data. Worst case: n comparisons, so O(n). See topic 10 for the pseudocode.

Binary search

Works only on sorted data. Look at the middle item: if it is the target, stop; if the target is larger, discard the lower half; otherwise discard the upper half. Repeat on the remaining half. Each comparison halves the search space, so the worst case is about log2 n comparisons: O(log n). For 1000 items that's at most 10 comparisons, against up to 1000 for a linear search.

FUNCTION BinarySearch(SearchItem : INTEGER) RETURNS INTEGER
    DECLARE Low, High, Mid : INTEGER
    Low ← 1
    High ← 100                         // global array Data[1:100], sorted
    WHILE Low <= High
        Mid ← (Low + High) DIV 2
        IF Data[Mid] = SearchItem THEN
            RETURN Mid
        ELSE
            IF Data[Mid] < SearchItem THEN
                Low ← Mid + 1
            ELSE
                High ← Mid - 1
            ENDIF
        ENDIF
    ENDWHILE
    RETURN -1                          // not found
ENDFUNCTION
def binary_search(items, target):
    low, high = 0, len(items) - 1
    while low <= high:
        mid = (low + high) // 2
        if items[mid] == target:
            return mid
        elif items[mid] < target:
            low = mid + 1
        else:
            high = mid - 1
    return -1

Sorting

Insertion sort

Builds a sorted section at the start of the array. Each new item is taken out and inserted into its correct place in the sorted section by shifting larger items one place right. Efficient for small or nearly sorted data (best case O(n)); worst case O(n²).

PROCEDURE InsertionSort()
    DECLARE I, J, Key : INTEGER
    FOR I ← 2 TO 10                    // global array Items[1:10]
        Key ← Items[I]
        J ← I - 1
        WHILE J >= 1 AND Items[J] > Key
            Items[J + 1] ← Items[J]
            J ← J - 1
        ENDWHILE
        Items[J + 1] ← Key
    NEXT I
ENDPROCEDURE
def insertion_sort(items):
    for i in range(1, len(items)):
        key = items[i]
        j = i - 1
        while j >= 0 and items[j] > key:
            items[j + 1] = items[j]
            j -= 1
        items[j + 1] = key

The bubble sort from topic 10 is also O(n²) in the worst case, and O(n) in the best case when a flag stops it early. In practice insertion sort usually makes fewer comparisons and moves.

Implementing abstract data types

Stack and queue

Both can be built from an array with pointers (see topic 10). A circular queue uses MOD so the pointers wrap round to the start of the array:

SIZE = 5
queue = [None] * SIZE
front, rear, count = 0, -1, 0

def enqueue(item):
    global rear, count
    if count == SIZE:
        return False                     # queue full
    rear = (rear + 1) % SIZE
    queue[rear] = item
    count += 1
    return True

def dequeue():
    global front, count
    if count == 0:
        return None                      # queue empty
    item = queue[front]
    front = (front + 1) % SIZE
    count -= 1
    return item

Linked list

In Paper 4 a linked list is usually an array of nodes, each with a data field and a pointer field. A start pointer marks the first node, a free pointer marks the first unused node, and −1 means null. The free nodes are themselves linked together into a free list.

NULL = -1

class Node:
    def __init__(self):
        self.data = ""
        self.pointer = NULL

nodes = [Node() for _ in range(10)]
for i in range(9):
    nodes[i].pointer = i + 1             # link all nodes into the free list
start, free = NULL, 0

def insert(item):                        # keeps the list in ascending order
    global start, free
    if free == NULL:
        print("List is full")
        return
    new = free
    free = nodes[free].pointer           # take the first free node
    nodes[new].data = item
    previous, current = NULL, start
    while current != NULL and nodes[current].data < item:
        previous, current = current, nodes[current].pointer
    if previous == NULL:                 # insert at the start
        nodes[new].pointer = start
        start = new
    else:                                # insert between previous and current
        nodes[new].pointer = current
        nodes[previous].pointer = new

def output_list():
    current = start
    while current != NULL:
        print(nodes[current].data)
        current = nodes[current].pointer

To delete a node: find it, keeping track of the previous node; set the previous node's pointer to the deleted node's pointer (or move the start pointer if it was first); then add the deleted node to the front of the free list.

Binary tree

Each node has a left pointer and a right pointer. In a binary search tree, everything in a node's left subtree is smaller than it and everything in its right subtree is larger, so searching, like a binary search, halves the possibilities at each step.

50307020406080
Inserting 50, 30, 70, 20, 40, 60, 80 in that order gives this tree.
TraversalOrderResult for the tree above
In-orderleft, root, right20 30 40 50 60 70 80 (sorted order)
Pre-orderroot, left, right50 30 20 40 70 60 80
Post-orderleft, right, root20 40 30 60 80 70 50
class TreeNode:
    def __init__(self, data):
        self.data = data
        self.left = None
        self.right = None

def insert(node, data):
    if node is None:
        return TreeNode(data)
    if data < node.data:
        node.left = insert(node.left, data)
    else:
        node.right = insert(node.right, data)
    return node

def in_order(node):
    if node is not None:
        in_order(node.left)
        print(node.data)
        in_order(node.right)

root = None
for value in [50, 30, 70, 20, 40, 60, 80]:
    root = insert(root, value)
in_order(root)

Graphs and dictionaries

A graph ADT can be stored as an adjacency matrix (a 2D array where cell [i, j] holds the weight of the edge from i to j, or 0) or an adjacency list (each node stores a list of its neighbours). A dictionary ADT stores key-value pairs and looks values up by key; it is usually implemented as a hash table, giving close to O(1) lookup.

graph = {"A": {"B": 4, "C": 2}, "B": {"A": 4, "C": 1, "D": 5}}   # adjacency list
phone_book = {"Sara": "0300-1234567"}                             # dictionary
phone_book["Ali"] = "0321-7654321"
print(phone_book["Sara"])

Comparing algorithms: Big O

Big O notation describes how an algorithm's time (or memory) requirement grows as the size of the input, n, grows. It shows the worst-case order of growth, ignoring constants. Time complexity is about the number of steps; space complexity is about the memory needed.

Big ONameExample
O(1)ConstantAccessing an array element by index; push or pop on a stack
O(log n)LogarithmicBinary search; searching a balanced binary search tree
O(n)LinearLinear search; traversing a linked list
O(n log n)LinearithmicEfficient sorts such as merge sort
O(n²)Polynomial (quadratic)Bubble sort and insertion sort (worst case); nested loops over the data
O(2n)ExponentialNaive recursive Fibonacci; trying every subset

Recursion

A recursive subroutine is defined in terms of itself: it calls itself. Every recursive subroutine needs:

  • a base case: a condition where it returns a value without calling itself, which stops the recursion;
  • a general (recursive) case: where it calls itself with a different argument;
  • each call must move closer to the base case.
FUNCTION Factorial(N : INTEGER) RETURNS INTEGER
    IF N = 0 THEN
        RETURN 1                           // base case
    ELSE
        RETURN N * Factorial(N - 1)        // general case
    ENDIF
ENDFUNCTION
Winding (calls)Unwinding (returns)
Factorial(4) calls Factorial(3)Factorial(4) returns 4 × 6 = 24
Factorial(3) calls Factorial(2)Factorial(3) returns 3 × 2 = 6
Factorial(2) calls Factorial(1)Factorial(2) returns 2 × 1 = 2
Factorial(1) calls Factorial(0)Factorial(1) returns 1 × 1 = 1
Factorial(0) is the base caseFactorial(0) returns 1

How a compiler implements recursion

Each call pushes a stack frame onto the call stack, holding the return address, the parameters and the local variables for that call. When the base case is reached, frames are popped one at a time as each call returns its value to the call below it (unwinding). If the recursion is too deep (or never reaches a base case), the stack runs out of memory: a stack overflow.

Recursion vs iteration: recursive solutions can be shorter and more natural for problems that are recursive by nature (tree traversal, divide and conquer). But they use more memory, because of the stack frames, and are often slower because of the call overhead.

Exam-style questions

1Paper 3 style

An array holds these values at indices 1 to 10: 3, 8, 12, 17, 23, 31, 39, 44, 50, 61. The binary search algorithm above is used.

(a)
State the values of Mid examined when searching for 44.
[2]
(b)
State the values of Mid examined when searching for 20, and explain how the algorithm ends.
[3]
(c)
State the precondition for a binary search, and its Big O time complexity.
[2]
Show mark scheme
  • (a) Mid = 5 (value 23, too small, so Low = 6)
  • (a) Mid = 8 (value 44, found)
  • (b) Mid = 5 (23 > 20, High = 4), then Mid = 2 (8 < 20, Low = 3)
  • (b) Then Mid = 3 (12, Low = 4), then Mid = 4 (17, Low = 5)
  • (b) Low (5) is now greater than High (4), so the loop ends and −1 (not found) is returned.
  • (c) The data must be sorted.
  • (c) O(log n)
2Paper 4 style
Write a program in Python (or pseudocode) for a procedure that sorts a global array of 10 integers into descending order using an insertion sort.
[6]
Show mark scheme
numbers = [12, 5, 33, 7, 21, 9, 40, 1, 18, 26]

def insertion_sort_descending():
    for i in range(1, len(numbers)):
        key = numbers[i]
        j = i - 1
        while j >= 0 and numbers[j] < key:
            numbers[j + 1] = numbers[j]
            j -= 1
        numbers[j + 1] = key
  • Outer loop from the second element to the last
  • Store the current element as the key
  • Inner conditional loop that checks the index stays in range
  • Comparison reversed for descending order (< key)
  • Shift elements one place up and decrement the index
  • Insert the key in the correct position after the inner loop
3Paper 3 style
FUNCTION Calc(N : INTEGER) RETURNS INTEGER
    IF N = 0 THEN
        RETURN 0
    ELSE
        RETURN (N MOD 10) + Calc(N DIV 10)
    ENDIF
ENDFUNCTION
(a)
Trace the function call Calc(472), showing each call and the value returned.
[3]
(b)
State the purpose of the function.
[1]
(c)
Explain how a stack is used when this recursive function is executed.
[3]
Show mark scheme
  • (a) Calc(472) → 2 + Calc(47); Calc(47) → 7 + Calc(4); Calc(4) → 4 + Calc(0)
  • (a) Calc(0) returns 0 (base case); Calc(4) returns 4; Calc(47) returns 11
  • (a) Calc(472) returns 13
  • (b) It returns the sum of the digits of N.
  • (c) Each call pushes a stack frame containing the return address, the parameter N and local data.
  • (c) Calls continue to be pushed until the base case (N = 0) is reached.
  • (c) Frames are then popped in reverse order, each returning its value to the calling call (unwinding).
4Paper 3 style
(a)
The values 45, 22, 67, 12, 30, 51 and 89 are inserted, in that order, into an empty binary search tree. Draw the tree.
[3]
(b)
Give the output of a pre-order traversal and a post-order traversal of your tree.
[2]
Show mark scheme
  • (a) 45 is the root; 22 is its left child and 67 its right child.
  • (a) 12 is the left child and 30 the right child of 22.
  • (a) 51 is the left child and 89 the right child of 67.
  • (b) Pre-order: 45 22 12 30 67 51 89
  • (b) Post-order: 12 30 22 51 89 67 45
5Paper 3 style
(a)
State the Big O time complexity of: a linear search; a bubble sort (worst case); accessing an element of an array by its index; a binary search.
[4]
(b)
Describe how a node is removed from a linked list that is implemented using an array and a free list.
[4]
Show mark scheme
  • (a) Linear search O(n)
  • (a) Bubble sort O(n²)
  • (a) Array access O(1)
  • (a) Binary search O(log n)
  • (b) Traverse the list from the start pointer to find the node, recording the previous node.
  • (b) If it is the first node, set the start pointer to the node's pointer…
  • (b) …otherwise, set the previous node's pointer to the deleted node's pointer.
  • (b) Return the node to the free list: set its pointer to the free pointer, and set the free pointer to the node.

A programming paradigm is a style of programming, with its own way of structuring a solution. This topic covers object-oriented programming in depth (a Paper 4 favourite), declarative programming with Prolog-style facts and rules, random-access files and exception handling.

Programming paradigms

Low-level
Programming close to the hardware in assembly language, using the processor's instruction set and addressing modes: immediate, direct, indirect, indexed and relative (see topic 4).
Imperative (procedural)
The program is a sequence of statements that change the program's state, organised into procedures and functions. You state how to solve the problem step by step (see topic 11).
Object-oriented
The program is built from objects that combine data (attributes) and the methods that act on that data, modelling things in the problem.
Declarative
You state what is true (facts and rules) and what you want to find (a goal), and the language works out how to satisfy it. Prolog and SQL are declarative.

Object-oriented programming

Class
A blueprint or template defining the attributes and methods that its objects will have.
Object (instance)
A single example of a class, created from it, with its own values for the attributes. Creating one is called instantiation.
Attribute (property)
A data item stored in an object.
Method
A procedure or function defined in a class that acts on an object's data.
Constructor
The method that runs when an object is created, usually to set its initial attribute values.
Encapsulation
Keeping an object's attributes and methods together in the class, and making attributes private so they can only be accessed through the object's public methods. This protects the data from being changed in invalid ways.
Getter and setter
Public methods that return (get) or change (set) a private attribute. A setter can validate the new value first.
Inheritance
A subclass (derived class) takes on all the attributes and methods of its superclass (base class) and can add its own, so code is reused rather than rewritten.
Polymorphism
A method with the same name behaves differently depending on the class of the object it belongs to, because a subclass overrides the inherited method with its own version.
Containment (aggregation)
One class contains objects of another class as attributes: a "has a" relationship, such as a Department that has Employees.
Department - Staff : Employee list+ AddEmployee(E)+ TotalPay(Hours) : REAL Employee - Name : STRING- HourlyRate : REAL + NEW(Name, Rate)+ GetName() : STRING+ CalculatePay(Hours) : REAL Manager - Bonus : REAL+ NEW(Name, Rate, Bonus)+ CalculatePay(Hours) : REAL
In a class diagram, − marks a private member and + a public one. The hollow triangle points from a subclass to its superclass (inheritance). The hollow diamond sits on the containing class (aggregation).

In Cambridge pseudocode

CLASS Employee
    PRIVATE Name : STRING
    PRIVATE HourlyRate : REAL
    PUBLIC PROCEDURE NEW(GivenName : STRING, GivenRate : REAL)
        Name ← GivenName
        HourlyRate ← GivenRate
    ENDPROCEDURE
    PUBLIC FUNCTION GetName() RETURNS STRING
        RETURN Name
    ENDFUNCTION
    PUBLIC PROCEDURE SetHourlyRate(NewRate : REAL)
        IF NewRate > 0 THEN
            HourlyRate ← NewRate
        ENDIF
    ENDPROCEDURE
    PUBLIC FUNCTION CalculatePay(Hours : REAL) RETURNS REAL
        RETURN Hours * HourlyRate
    ENDFUNCTION
ENDCLASS

CLASS Manager INHERITS Employee
    PRIVATE Bonus : REAL
    PUBLIC PROCEDURE NEW(GivenName : STRING, GivenRate : REAL, GivenBonus : REAL)
        SUPER.NEW(GivenName, GivenRate)
        Bonus ← GivenBonus
    ENDPROCEDURE
    PUBLIC FUNCTION CalculatePay(Hours : REAL) RETURNS REAL
        RETURN SUPER.CalculatePay(Hours) + Bonus
    ENDFUNCTION
ENDCLASS

DECLARE Boss : Manager
Boss ← NEW Manager("Ayesha", 2000, 15000)
OUTPUT Boss.CalculatePay(40)

In Python

class Employee:
    def __init__(self, name, hourly_rate):    # constructor
        self.__name = name                     # __ makes an attribute private
        self.__hourly_rate = hourly_rate

    def get_name(self):                        # getter
        return self.__name

    def set_hourly_rate(self, rate):           # setter with validation
        if rate > 0:
            self.__hourly_rate = rate

    def calculate_pay(self, hours):
        return hours * self.__hourly_rate


class Manager(Employee):                       # inheritance
    def __init__(self, name, hourly_rate, bonus):
        super().__init__(name, hourly_rate)
        self.__bonus = bonus

    def calculate_pay(self, hours):            # overrides the inherited method
        return super().calculate_pay(hours) + self.__bonus


class Department:                              # containment
    def __init__(self, name):
        self.__name = name
        self.__staff = []

    def add_employee(self, employee):
        self.__staff.append(employee)

    def total_pay(self, hours):
        total = 0
        for person in self.__staff:            # polymorphism: each object uses
            total += person.calculate_pay(hours)   # its own calculate_pay
        return total


sales = Department("Sales")
sales.add_employee(Employee("Bilal", 1500))
sales.add_employee(Manager("Ayesha", 2000, 15000))
print(sales.total_pay(40))                     # 60000 + 95000 = 155000

Declarative programming

A declarative program is a knowledge base of facts (things that are true) and rules (how new facts can be worked out). You then ask a goal (query), and the system searches the knowledge base for values that make it true. Constants start with a lower-case letter; variables start with an upper-case letter.

01 parent(ali, sara).
02 parent(ali, omar).
03 parent(sara, zain).
04 parent(sara, hina).
05 male(ali).
06 male(omar).
07 male(zain).
08 female(sara).
09 female(hina).
10 father(X, Y) IF parent(X, Y) AND male(X).
11 grandparent(X, Z) IF parent(X, Y) AND parent(Y, Z).

Cambridge papers usually write rules with IF and AND. In real Prolog these are written :- and a comma: father(X, Y) :- parent(X, Y), male(X).

GoalResult
male(omar)TRUE
parent(P, zain)P = sara
father(ali, Who)Who = sara; Who = omar
grandparent(ali, G)G = zain; G = hina
Instantiation
Giving a variable a value while trying to satisfy a goal. For grandparent(ali, G), Y is first instantiated to sara by clause 01.
Backtracking
When part of a goal fails, or to find further solutions, the system goes back to the most recent choice point and tries the next possible value. After finding G = zain and G = hina with Y = sara, it backtracks and tries Y = omar; parent(omar, Z) has no match, so there are no more solutions.

File processing

Text files store lines of characters (see topic 10). To store records, a random file lets a program jump straight to the record at a given position, which is how a hashed file from topic 13 is implemented.

DECLARE Student : StudentRecord
DECLARE Address : INTEGER
OPENFILE "Students.dat" FOR RANDOM

// write a record to the position given by a hash of its key
Address ← Hash(Student.StudentID)
SEEK "Students.dat", Address
PUTRECORD "Students.dat", Student

// read the record back from that position
SEEK "Students.dat", Address
GETRECORD "Students.dat", Student

CLOSEFILE "Students.dat"

In Python, objects can be written to and read from a binary file with the pickle module:

import pickle

def save_records(records, filename):
    with open(filename, "wb") as file:          # "wb" = write binary
        for record in records:
            pickle.dump(record, file)

def load_records(filename):
    records = []
    try:
        with open(filename, "rb") as file:      # "rb" = read binary
            while True:
                records.append(pickle.load(file))
    except EOFError:                            # reached the end of the file
        pass
    except FileNotFoundError:
        print("The file", filename, "does not exist.")
    return records

Exception handling

An exception is an unexpected event that happens while a program is running and disrupts its normal flow, such as a missing file, invalid input, division by zero or an index out of range. If it isn't handled, the program crashes. Exception handling catches the exception and runs code to deal with it, so the program can show a useful message, recover, or close safely without losing data.

def get_age():
    while True:
        try:
            age = int(input("Enter your age: "))   # may raise ValueError
            if age < 0:
                raise ValueError("Age can't be negative")
            return age
        except ValueError:
            print("Please enter a whole number of 0 or more.")

try:
    with open("scores.txt") as f:
        scores = [int(line) for line in f]
    print("Average:", sum(scores) / len(scores))  # may raise ZeroDivisionError
except FileNotFoundError:
    print("scores.txt was not found.")
except ZeroDivisionError:
    print("The file is empty.")
finally:
    print("Finished.")                             # always runs

Exam-style questions

1Paper 3 style
Explain what is meant by encapsulation, inheritance and polymorphism in object-oriented programming.
[6]
Show mark scheme
  • Encapsulation: data (attributes) and the methods that act on it are combined in one class…
  • …and the attributes are private, so they can only be accessed via the class's public methods (getters and setters).
  • Inheritance: a subclass takes on the attributes and methods of its superclass…
  • …and can add its own attributes and methods, so code is reused.
  • Polymorphism: a method inherited from a superclass is redefined (overridden) in a subclass…
  • …so the same method call behaves differently depending on the object's class.
2Paper 4 style

A library needs a class Book with the private attributes Title (string), Author (string) and OnLoan (Boolean).

(a)
Write program code for the class, including a constructor that takes the title and author and sets OnLoan to FALSE, and a getter for each attribute.
[5]
(b)
Write a method LendBook() that sets OnLoan to TRUE and returns TRUE if the book is available, or returns FALSE if it is already on loan.
[3]
Show mark scheme
class Book:
    def __init__(self, title, author):
        self.__title = title
        self.__author = author
        self.__on_loan = False

    def get_title(self):
        return self.__title

    def get_author(self):
        return self.__author

    def get_on_loan(self):
        return self.__on_loan

    def lend_book(self):
        if self.__on_loan:
            return False
        self.__on_loan = True
        return True
  • (a) Class declaration
  • (a) Constructor with title and author parameters
  • (a) Attributes declared private and assigned from the parameters
  • (a) OnLoan initialised to FALSE
  • (a) Three getters that each return the correct attribute
  • (b) Method checks whether OnLoan is already TRUE and returns FALSE if so
  • (b) Otherwise sets OnLoan to TRUE
  • (b) …and returns TRUE
3Paper 3 style

Use the family knowledge base in the notes above (clauses 01 to 11).

(a)
State the result of each goal: female(X), parent(sara, C), father(sara, zain).
[3]
(b)
Write a rule, clause 12, to define mother(X, Y).
[2]
(c)
Write a clause to state that zain is a parent of ayan.
[1]
Show mark scheme
  • (a) X = sara; X = hina
  • (a) C = zain; C = hina
  • (a) FALSE (sara is not male)
  • (b) mother(X, Y) IF parent(X, Y)…
  • (b) …AND female(X).
  • (c) parent(zain, ayan).
4Paper 4 style
(a)
Explain what is meant by an exception, and why programs should handle them.
[2]
(b)
Write program code for a function that asks the user for a number of items, and keeps asking until a valid positive integer is entered. Use exception handling.
[4]
Show mark scheme
def get_quantity():
    while True:
        try:
            quantity = int(input("Number of items: "))
            if quantity > 0:
                return quantity
            print("The number must be positive.")
        except ValueError:
            print("That is not a whole number.")
  • (a) An unexpected event or error that occurs while a program is running (such as invalid input or a missing file)…
  • (a) …which would make the program crash if not handled, so handling lets it recover or end gracefully.
  • (b) Loop that repeats until a valid value is entered
  • (b) Input converted to an integer inside a try block
  • (b) Except block catches the conversion error and outputs a message
  • (b) Check that the value is positive, then return it
5Paper 3 style
A random file Stock.dat stores records of type StockItem. Write pseudocode for a function GetItem() that takes a record position as a parameter and returns the record stored at that position.
[4]
Show mark scheme
FUNCTION GetItem(Position : INTEGER) RETURNS StockItem
    DECLARE Item : StockItem
    OPENFILE "Stock.dat" FOR RANDOM
    SEEK "Stock.dat", Position
    GETRECORD "Stock.dat", Item
    CLOSEFILE "Stock.dat"
    RETURN Item
ENDFUNCTION
  • Function header with an INTEGER parameter, returning StockItem
  • Open the file for RANDOM and close it
  • SEEK the position
  • GETRECORD into a local variable and return it