Paper 1 · Theory Fundamentals
Written paper assessing the theory of Sections 1 to 8: information representation, communication, hardware, processor fundamentals, system software, security, ethics and databases. Answer all questions.
Revision notes for all twenty sections of the 9618 syllabus, with worked examples and exam tips for every paper. Section 1 is free — sign in with Google to unlock Sections 2–20.
Exam map: AS = Papers 1–2 · A Level = all four papers · 75 marks each · No calculators in any paper · June and November series · Exam target: May/June 2027
Cambridge 9618 · Notes by Tr. Wai Lin Htet
Tap the bits. Turn them on and off and watch the value change.
At AS Level you take Papers 1 and 2. At A Level you take all four papers. No calculators may be used in any paper. Exams are available in the June and November series.
Written paper assessing the theory of Sections 1 to 8: information representation, communication, hardware, processor fundamentals, system software, security, ethics and databases. Answer all questions.
Written paper assessing Sections 9 to 12: algorithm design, data types and structures, programming and software development. Answers are written in pseudocode.
Written paper assessing Sections 13 to 20: advanced data representation, internet technologies, hardware and virtual machines, system software, security, artificial intelligence, computational thinking and further programming. Answer all questions.
Practical examination on a computer, without internet or email. Assesses Sections 19 to 20 (except low-level and declarative programming). Use Java, Visual Basic (.NET) or Python in console mode, and submit complete program code with evidence of testing.
The syllabus and revision notes for this course are free — ask your teacher for a copy, or get them from Cambridge International and zNotes.
The official syllabus: the paper structure, the content of all twenty sections, and the assessment objectives. This is the document the notes on this page follow. Available free from Cambridge International — ask your teacher for a copy.
Two short revision-note booklets covering the AS topics. Please note they were written for the previous syllabus, so their section numbers differ from 9618. Free from zNotes — ask your teacher for a copy.
Cambridge International AS & A Level Computer Science Coursebook — David Watson & Helen Williams, Hodder Education, 2019. ISBN 9781510457591. Endorsed by Cambridge Assessment International Education; the chapters follow the 9618 syllabus in order. Ask your teacher where to buy a copy.
No sign-in needed for Section 1 — here is a sample of how the notes teach, so you can see the style before you join.
+23 in 8 bits: 00010111 Invert the bits: 11101000 Add 1: 11101001 So -23 = 11101001
Found ← FALSE
Index ← 1
WHILE Index <= 8 AND Found = FALSE
IF Numbers[Index] = Target THEN
Found ← TRUE
ELSE
Index ← Index + 1
ENDIF
ENDWHILE
Twenty sections in syllabus order. Section 1 is free to read — sign in with Google to unlock Sections 2–20.
1) Sign in with Google on the login page. 2) Your teacher approves your account. 3) Your courses appear on your dashboard — open this page from there.
Theory notes for Sections 1 to 12, in syllabus order. Each section states what you must be able to do, explains the ideas, and ends with a worked example and exam tips.
Binary, denary, hexadecimal and BCD; two's complement; bitmaps, vectors and sound; compression.
Computers store everything as patterns of 0s and 1s. Denary is base 10, binary is base 2 and hexadecimal is base 16. Hexadecimal is a shorthand for binary: each hex digit stands for exactly four bits, which is why memory addresses and colour codes are usually written in hex. BCD is different again — each denary digit is stored as its own four-bit group, which is why BCD is used in displays and financial systems where exact decimal digits matter.
Negative integers are normally stored in two's complement: to find the two's complement of a positive number, invert every bit and add 1. In 8 bits, +5 is 00000101, so −5 is 11111011. The big advantage is that the same addition circuit works for positive and negative numbers. Overflow happens when a result needs more bits than are available — for example, adding two large positive 8-bit numbers and getting a result that looks negative.
Characters are stored as numbers too. ASCII uses 7 bits (128 characters: letters, digits, punctuation and control codes), extended ASCII uses 8 bits (256 characters), and Unicode uses 16 or more bits so it can represent almost every writing system in the world. You are not expected to memorise any particular character codes — but you must know which set to use and why.
A bitmap image is a grid of pixels. Its file size depends on three things: the number of pixels (image resolution) and the number of bits used for each pixel (colour depth). A useful formula to learn is:
Bitmap file size (bits) = image width in pixels × image height in pixels × colour depth in bits. Divide by 8 for bytes. Raising the resolution or the colour depth makes the picture sharper but the file bigger.
A vector graphic is not a grid at all — it is a list of drawing objects (lines, curves, shapes) with properties such as position, size, fill colour and line thickness. Vectors can be scaled to any size without losing quality, so they suit logos and diagrams; bitmaps suit photographs, where every pixel can be a different colour.
Sound is analogue, so it must be sampled: the sound wave is measured at regular intervals (the sampling rate, in samples per second) and each measurement is stored to a fixed precision (the sampling resolution, in bits). A higher sampling rate captures higher frequencies and a higher resolution captures quieter and louder detail — both make the file bigger. CD-quality sound is sampled 44,100 times per second at 16 bits.
Lossless compression throws away nothing: the original file can be rebuilt exactly. Lossy compression throws away detail the eye or ear is unlikely to notice, so the file is much smaller but the original can never be recovered. Use lossless for text and data, and lossy for photographs, music and video where a little lost detail does not matter.
Run-length encoding (RLE) is the simplest lossless method: a run of identical values is stored as one value plus a count. The string AAAAABBBCC becomes 5A 3B 2C. RLE works well on images with large flat areas of one colour and badly on photographs, where neighbouring pixels are almost never identical.
(a) Write −23 as an 8-bit two's complement number. 23 in binary is 00010111. Invert the bits: 11101000. Add 1: 11101001. So −23 = 11101001. Check: the leftmost bit is 1, which marks a negative number.
(b) A bitmap is 800 × 600 pixels with a colour depth of 24 bits. File size = 800 × 600 × 24 = 11,520,000 bits = 1,440,000 bytes (÷ 8), about 1.4 MB before any compression or file header.
Type in any box and the other two follow. This is the same conversion the exam asks for, up to 8 bits.
This section is for approved SrWL Learning students. Sign in with Google to unlock it — Section 1 is free to read now.
LANs and WANs, client-server and peer-to-peer, topologies, cloud computing, media and hardware, IP addressing.
A LAN (local area network) covers a small area such as a school or office, is fast, and is usually owned by one organisation. A WAN (wide area network) covers a large area — the internet is the largest WAN — and is slower and owned by many organisations. In a client-server network, a central server provides services and controls security; in a peer-to-peer network, every computer is equal and shares files directly with the others. Client-server suits a school (central backups, one login, controlled access); peer-to-peer suits a small home network (cheap, no server to maintain).
A thin client does almost no processing itself — it relies on the server for programs and storage. A thick client has its own processor, memory and storage and can work on its own. Thin clients are cheap and easy to manage centrally; thick clients keep working if the network fails.
| Topology | How it works | Strength | Weakness |
|---|---|---|---|
| Bus | All computers share one cable; data travels along the bus to its destination. | Cheap and simple to set up. | If the main cable fails, the whole network fails; collisions slow it down. |
| Star | Every computer connects to a central switch or hub. | One cable failing affects only one computer; easy to add computers. | If the central switch fails, the whole network fails. |
| Mesh | Computers connect to several others, so there are many routes. | Very reliable — data can take another route if one link fails. | Expensive: lots of cables and connections. |
| Hybrid | A mix of two or more topologies, e.g. star networks joined by a bus backbone. | Combines the strengths of each part. | Complex and expensive to design and manage. |
Data travels as packets. Wired media include copper cable (cheap, but signals weaken over distance and suffer interference) and fibre-optic cable (light pulses, very fast, immune to interference, but expensive to install). Wireless media include radio waves (WiFi), microwaves and satellites (good for remote areas, but slower and affected by weather and interference).
Key LAN hardware: a switch connects computers in a LAN and sends each packet only to its destination; a NIC (network interface card) connects a computer to the network and holds its MAC address; a WAP (wireless access point) lets wireless devices join a wired network; a bridge joins two similar networks; a repeater boosts a weakening signal. A router connects different networks together — it reads the destination IP address of each packet and forwards it towards the next network on its journey.
Every device on a network has a MAC address (a permanent hardware address built into the NIC) and an IP address (a logical address that can change). IPv4 addresses are 32 bits written as four denary numbers (for example 192.168.1.10); IPv6 addresses are 128 bits written in hexadecimal, introduced because IPv4 addresses are running out. DNS (Domain Name System) translates human-readable names such as wailinhtet.com into IP addresses.
Ethernet is the standard way computers share a cable. To avoid collisions, it uses CSMA/CD: a computer listens to check the cable is free, sends its data, and if two computers send at the same time (a collision) both stop, wait a random time and try again. Bit streaming sends audio or video as a continuous stream — real-time (live, cannot be paused) or on-demand (stored, can be paused). A higher bit rate means better quality but needs a faster connection.
Finally, the internet is the network of networks; the World Wide Web is a service that runs on it (web pages linked by hyperlinks). Cloud computing means using storage and software on remote servers over the internet: a public cloud is shared by many customers, a private cloud is used by one organisation only. Cloud computing cuts the cost of buying and maintaining hardware, but it needs a reliable internet connection and raises questions about who controls your data.
Question: A school has 200 computers in 8 classrooms and wants central control of logins, files and printing. Recommend a topology and a network model, giving reasons.
Answer: Use a star topology in each classroom, with the classroom switches joined into a hybrid network, and a client-server model. Reasons: in a star, one faulty cable affects only one computer, so a fault does not stop a whole class; the server gives one login per student, central backups and controlled printing; and new computers are easy to add to a star. A bus would be a poor choice because one cable fault would stop a whole classroom, and peer-to-peer would give no central control over 200 users.
This section is for approved SrWL Learning students. Sign in with Google to unlock it — Section 1 is free to read now.
Input, output and storage devices; RAM and ROM; logic gates, truth tables and circuits.
RAM is volatile working memory: its contents are lost when the power is off. SRAM (static RAM) uses flip-flops, is fast and expensive, and is used for cache memory. DRAM (dynamic RAM) stores each bit as a charge in a capacitor, is slower and cheaper, and must be refreshed regularly — it is the main memory of a computer. ROM is non-volatile and holds the start-up instructions: PROM can be written once, EPROM can be erased with ultraviolet light and rewritten, and EEPROM can be erased electrically.
Secondary storage keeps data when the power is off. Magnetic storage (hard disk drives) is cheap with a large capacity but has moving parts and is relatively slow. Optical storage (CD, DVD, Blu-ray) is cheap and portable but holds less and is slower to write. Solid-state storage (SSD, USB flash, NAND flash) has no moving parts, is fast and silent, but costs more per gigabyte and wears out after many write cycles.
Each gate takes binary inputs and produces one binary output. The six gates you must know are:
| A | B | NOT A | A AND B | A OR B | A NAND B | A NOR B | A XOR B |
|---|---|---|---|---|---|---|---|
| 0 | 0 | 1 | 0 | 0 | 1 | 1 | 0 |
| 0 | 1 | 1 | 0 | 1 | 1 | 0 | 1 |
| 1 | 0 | 0 | 0 | 1 | 1 | 0 | 1 |
| 1 | 1 | 0 | 1 | 1 | 0 | 0 | 0 |
In words: AND is 1 only when both inputs are 1; OR is 1 when at least one input is 1; XOR is 1 when the inputs are different; NAND and NOR are AND and OR followed by NOT. A Boolean expression describes a circuit in symbols, for example X = (A AND B) OR C. To build a truth table, work out the intermediate columns first (for example A AND B), then combine them for X — never try to jump straight to the final column.
Tap A and B and watch every gate output change.
Question: A circuit has X = (A AND B) OR NOT C. Complete the truth table row where A = 1, B = 0, C = 1.
Answer: Work column by column. A AND B = 1 AND 0 = 0. NOT C = NOT 1 = 0. Then X = 0 OR 0 = 0. So for A = 1, B = 0, C = 1, X = 0. Building the full table the same way (8 rows for three inputs) gives X = 1 only when A AND B is 1, or C is 0.
This section is for approved SrWL Learning students. Sign in with Google to unlock it — Section 1 is free to read now.
Von Neumann architecture, the fetch-decode-execute cycle, registers, assembly language and bit manipulation.
Almost every computer follows the Von Neumann architecture: one memory holds both program instructions and data, and a central processor fetches instructions from memory one at a time and executes them. The processor has an ALU (arithmetic logic unit, which does calculations and comparisons), a control unit (which directs the whole process), a clock (which sends regular pulses to time every step) and three buses: the address bus (one-way: processor to memory, carrying the address wanted), the data bus (two-way: carrying the data or instruction itself) and the control bus (carrying timing and control signals).
| Register | Role |
|---|---|
| PC (program counter) | Holds the address of the next instruction to be fetched. |
| MAR (memory address register) | Holds the address of the memory location being read from or written to. |
| MDR (memory data register) | Holds the data or instruction that has just been read from, or is about to be written to, memory. |
| CIR (current instruction register) | Holds the instruction currently being decoded and executed. |
| ACC (accumulator) | Holds the result of a calculation while it is being worked on. |
| Status register | Holds flags, for example whether the last result was zero or negative. |
The fetch-decode-execute cycle repeats for every instruction: fetch — copy the instruction at the address in the PC into the CIR (and increase the PC); decode — the control unit works out what the instruction means; execute — carry it out, which may move data or change the PC. An interrupt is a signal that makes the processor stop what it is doing, save its place, run an interrupt service routine (for example to handle a key press or a printer finishing), and then return to the saved place.
Machine code is binary — the only language the processor understands directly. Assembly language is the same thing written with readable mnemonics: each instruction has an op-code (what to do, such as ADD or LDM) and an operand (the data or address to work on). An assembler translates assembly language into machine code.
| Addressing mode | What the operand means | Example |
|---|---|---|
| Immediate | The operand is the value itself. | LDM #25 loads the value 25. |
| Direct | The operand is the address of the value. | LDM 25 loads the value stored at address 25. |
| Indirect | The operand is the address of an address: the value at that address is itself an address. | LDM (25) loads the value at the address stored at address 25. |
| Indexed | The operand address is added to the index register (IX). | LDM 25, IX loads the value at address 25 + IX. |
| Relative | The operand is added to the PC — used for jumps. | JMP +4 jumps four instructions ahead. |
A mask is a pattern of bits used with AND, OR or XOR to change selected bits and leave the rest alone: AND with 0 clears a bit (and with 1 leaves it unchanged), so AND tests or clears bits; OR with 1 sets a bit; XOR with 1 inverts (toggles) a bit. For example, to set bit 2 of the register value 00001000, OR it with the mask 00000100 to get 00001100. To test whether bit 3 is set, AND the value with 00001000 and check whether the result is zero.
LDM #0 ; load 0 into the accumulator STO 50 ; store the accumulator at address 50 LDM 51 ; load the value at address 51 ADD #5 ; add 5 STO 52 ; store the result at address 52 END
If memory location 51 holds 20, the trace is: ACC = 0, then address 50 holds 0; ACC = 20, then 20 + 5 = 25; address 52 holds 25. The routine copies 0 to address 50 and stores 25 (the value at 51, plus 5) at address 52. When tracing, write one row per instruction showing the ACC and any memory locations that change.
This section is for approved SrWL Learning students. Sign in with Google to unlock it — Section 1 is free to read now.
Operating systems, utility software, assemblers, compilers and interpreters.
The operating system is the software that manages the computer so that programs can run. Its main jobs are: process management (deciding which program gets the processor and for how long), memory management (giving each program the memory it needs and protecting programs from each other), file management (organising files and folders), device management (talking to printers, disks and other hardware through drivers) and user security (logins, passwords and access rights). Utility software helps maintain the system: a disk defragmenter gathers the scattered pieces of files back together so the disk reads faster, a backup utility copies files so they can be restored, and a compression tool shrinks files for storage or sending.
| What it does | Strength | Weakness | |
|---|---|---|---|
| Assembler | Translates assembly language into machine code. A two-pass assembler reads the program twice: the first pass records the addresses of labels, the second pass produces the machine code — this is how it resolves forward references to labels that appear later in the program. | Produces fast, small machine code. | Assembly language is slow to write and hard to read. |
| Compiler | Translates the whole high-level program into machine code (or bytecode) in one go, before it runs. | The finished program runs fast; errors are reported together so they can be fixed before running. | Must recompile the whole program after any change; the compiled code only runs on one type of processor. |
| Interpreter | Translates and runs the program one line at a time, while it runs. | Easy to test and debug — you can stop, fix and continue; the same program runs on any computer with an interpreter. | Runs more slowly, because translation happens every time; an error stops the program part-way through. |
Some languages compile to bytecode — an intermediate code that runs on a virtual machine (for example Java bytecode on the JVM). This gives a middle ground: the program is compiled once, but the bytecode runs on any computer that has the virtual machine.
Question: A student is writing a program to control a robot and needs to test small parts of the code again and again while the robot is running. Should the program be compiled or interpreted? Give two reasons.
Answer: Interpreted. First, an interpreter translates and runs one line at a time, so the student can test a small change immediately without recompiling the whole program. Second, when an error occurs the interpreter stops at that line, which makes it easier to find and fix the fault during development.
This section is for approved SrWL Learning students. Sign in with Google to unlock it — Section 1 is free to read now.
Threats and defences, encryption, validation and verification.
Malware is software written to harm: a virus attaches to files and spreads when they are shared, a worm spreads by itself across a network, and a trojan pretends to be useful software while secretly doing harm. Phishing is a fake email or message that tricks you into giving away passwords or bank details; pharming redirects you to a fake copy of a real website without you clicking anything; spyware secretly records what you type or where you browse; ransomware encrypts your files and demands payment to unlock them.
Defences work in layers. A firewall blocks unwanted network traffic; anti-virus software scans for and removes known malware; authentication (passwords, two-factor authentication, biometrics such as fingerprints) checks that a user is who they claim to be; access rights limit what each user can see or change; and encryption scrambles data so it cannot be read without the key. In symmetric encryption the same key encrypts and decrypts the data, so the key itself must be shared safely.
Data privacy and data security are different: privacy is about people's rights — who is allowed to collect and use personal data; security is about the safeguards that protect data from unauthorised access. A system can be secure (well protected) yet still breach privacy (collecting data it has no right to hold).
Validation checks whether data is sensible and acceptable when it is entered; verification checks whether data matches its original source. They are not the same thing, and the exam tests the difference.
| Validation method | What it checks | Example |
|---|---|---|
| Range check | The value is between sensible limits. | An exam mark must be 0–100. |
| Format check | The value matches a pattern. | A date must be DD/MM/YYYY. |
| Length check | The value has the right number of characters. | A password must be at least 8 characters. |
| Presence check | A value has been entered at all. | A name field must not be blank. |
| Check digit | The last digit matches a calculation on the others. | A barcode or ISBN number. |
Verification methods: double data entry (type the data twice and compare), visual checks (a person reads the entered data against the original), parity bits (an extra bit makes the number of 1s even or odd, catching single-bit errors in transmission) and checksums (a value calculated from the data, sent with it, and recalculated at the other end — if the two values differ, the data changed).
Question: A school enters students' exam marks into a system. (a) A mark of 105 is rejected. Which validation method is this, and why? (b) A teacher types each mark twice and the system compares the two entries. What is this called?
Answer: (a) A range check: marks must be between 0 and 100, and 105 is outside that range, so the value is not sensible. (b) Double data entry — a verification method: it checks that the entered data matches what was typed the first time, not whether the mark itself is sensible.
This section is for approved SrWL Learning students. Sign in with Google to unlock it — Section 1 is free to read now.
Ethical issues, codes of conduct, intellectual property, copyright and open-source licensing.
Computers create ethical questions that did not exist before: who owns data about you, who is responsible when an automated system makes a wrong decision, and how much should a program be allowed to watch its users? Professional codes of conduct — such as those of the ACM and the BCS — set out how computing professionals should behave: act honestly, protect users' privacy, do not harm others, and take responsibility for the systems you build. A code of conduct does not have the force of law, but breaking it can cost a professional their membership and reputation.
Intellectual property is the legal idea that creative work belongs to its creator. Copyright gives the creator the right to control copying; software piracy — copying or using software without a licence — is a breach of copyright and is illegal. A proprietary licence keeps the source code closed and charges for use; an open-source (FOSS) licence lets anyone see, change and share the code, usually for free. Open-source software is often developed by a community and can be inspected for security problems, but there may be no company to provide support or accept responsibility when it fails.
Artificial intelligence raises its own ethical issues: an AI system that decides who gets a loan or a job can inherit the biases in its training data; data profiling builds detailed pictures of people from their behaviour, often without their full understanding; and automated decisions can be hard to explain or appeal against. When you evaluate an ethical question in the exam, name the people affected, state what is gained and what is lost, and reach a reasoned conclusion — a one-sided answer scores less than a balanced one.
Question: A company uses AI to shortlist job applicants from their CVs. Discuss two ethical issues this raises.
Answer: First, bias: if the AI was trained on past hiring data that favoured one group of applicants, it will repeat that bias and reject qualified people unfairly — and the company may not even notice. Second, lack of transparency: applicants are not told how the decision was made and have no clear way to challenge it, so an unfair rejection cannot be corrected. A responsible company would audit the system for bias and keep a human in the final decision.
This section is for approved SrWL Learning students. Sign in with Google to unlock it — Section 1 is free to read now.
Flat files and relational databases, keys and E-R diagrams, DBMS features, SQL (DDL and DML).
A flat file stores all its data in one table. That causes three problems: data redundancy (the same fact is stored many times), inconsistency (updating one copy but not another leaves the data disagreeing with itself) and data-program dependency (changing the file's structure means changing every program that uses it). A relational database splits the data into linked tables, so each fact is stored once.
Each table has a primary key — a field (or combination of fields, called a compound key) that uniquely identifies each row. A foreign key is a primary key from another table, stored in this table to create the link. Referential integrity is the rule that a foreign key must match a real primary key in the other table — you cannot record an order for a customer who does not exist.
An E-R diagram shows the tables (entities) and how they relate: 1:1 (one row links to exactly one row, such as a person and their passport), 1:M (one row links to many, such as one customer and many orders) and M:N (many to many, such as students and courses). An M:N relationship cannot be built directly — it must be split into two 1:M relationships using a junction table in the middle.
A DBMS is the software that manages the database. It keeps a data dictionary (the definitions of every table, field and data type), enforces data security and access permissions (who can read or change what), and provides backup and recovery (so the database can be restored after a failure). Because programs use the DBMS instead of reading files directly, the data is independent of the programs — this is called logical data independence.
DDL (Data Definition Language) builds the structure; DML (Data Manipulation Language) works with the data inside it.
-- DDL: create a table with a primary key and a foreign key CREATE TABLE Orders ( OrderID INTEGER PRIMARY KEY, CustomerID INTEGER, OrderDate DATE, FOREIGN KEY (CustomerID) REFERENCES Customers (CustomerID) ); -- DML: list the names of customers who ordered after 1 June 2026 SELECT Customers.Name, Orders.OrderDate FROM Customers INNER JOIN Orders ON Customers.CustomerID = Orders.CustomerID WHERE Orders.OrderDate > '2026-06-01' ORDER BY Orders.OrderDate;
The INNER JOIN connects the two tables on the matching key, so each order appears next to the name of the customer who placed it. Other DML you must know: INSERT INTO (add a row), UPDATE (change a row), DELETE (remove a row), GROUP BY (group rows, for example to count orders per customer) and ORDER BY (sort the results).
Question: A library lends books to members. A member can borrow many books, and a book can be borrowed by many members over time. Draw the E-R design and name the keys.
Answer: This is an M:N relationship between Member and Book, so it needs a junction table — call it Loan. Member has primary key MemberID; Book has primary key BookID; Loan has a compound primary key (MemberID, BookID) — both fields are also foreign keys, one to Member and one to Book — plus fields such as DateBorrowed and DateReturned. The junction table turns one M:N relationship into two 1:M relationships, and referential integrity stops a loan being recorded for a member or book that does not exist.
This section is for approved SrWL Learning students. Sign in with Google to unlock it — Section 1 is free to read now.
Computational thinking, flowcharts and pseudocode, linear and binary search, bubble sort, trace tables.
| Algorithm | How it works | When to use it |
|---|---|---|
| Linear search | Check each item in turn, from the first to the last, until you find the one you want. | Any list, in any order. Simple, but slow for long lists. |
| Binary search | Look at the middle item of a sorted list: if it is too big, search the left half; if too small, search the right half; repeat. | Only on a sorted list. Very fast — it halves the search space at every step. |
| Bubble sort | Compare neighbouring pairs and swap them if they are in the wrong order; repeat passes until a whole pass makes no swaps. | Small lists, or teaching the idea of sorting. Slow for long lists. |
A trace table is how you prove an algorithm works — and how you find its bugs. Write one column for each variable, one row for each step, and update the values exactly as the algorithm would. If the trace table disagrees with what you expected, the algorithm (or your understanding of it) is wrong.
Question: Use binary search to find 42 in the sorted list [5, 12, 23, 31, 42, 57, 68, 79]. Show the low, high and mid positions at each step.
Answer: Low = 1, High = 8. Mid = (1 + 8) div 2 = 4, value 31. 31 < 42, so search the right half: Low = 5. Mid = (5 + 8) div 2 = 6, value 57. 57 > 42, so search the left half: High = 5. Mid = (5 + 5) div 2 = 5, value 42. Found at position 5, after three comparisons. A linear search would have needed five.
This section is for approved SrWL Learning students. Sign in with Google to unlock it — Section 1 is free to read now.
Primitive types, records and arrays, text files, abstract data types: stacks, queues and linked lists.
Choosing the right data type matters: an age is an INTEGER, a price is a REAL, a single letter is a CHAR, a name is a STRING, a yes/no answer is a BOOLEAN, and a date of birth is a DATE. A record groups different types of data about one thing under one name — for example a student record with a name (STRING), an age (INTEGER) and a grade (CHAR). In pseudocode:
TYPE Student DECLARE Name : STRING DECLARE Age : INTEGER DECLARE Grade : CHAR ENDTYPE DECLARE ClassList : ARRAY[1:30] OF Student
An array stores many values of the same type under one name, reached by an index. A one-dimensional array is a list (for example Scores[1:10]); a two-dimensional array is a table (for example Grid[1:5, 1:5] for a board game). Arrays are fixed in size and indexed from a known starting point — know whether your array starts at 0 or 1, because the exam tests this.
A sequential file is read from the start to the end, one record at a time; a random file lets you jump straight to any record. Text files are usually sequential. The pseudocode you must know is:
OPENFILE "results.txt" FOR READ
READFILE "results.txt", Line
WHILE NOT EOF("results.txt")
OUTPUT Line
READFILE "results.txt", Line
ENDWHILE
CLOSEFILE "results.txt"
Always close a file after using it, and always check for the end of file (EOF) when reading — reading past the end of a file is a common error.
A stack is last-in, first-out (LIFO): you push items on the top and pop them off the top, like a pile of plates. A queue is first-in, first-out (FIFO): items join at the back and leave from the front, like a queue of people. A linked list is a chain of nodes, where each node holds data and a pointer to the next node — items can be inserted or removed anywhere in the chain without moving the others. All three can be built from a one-dimensional array: a stack needs a top pointer, a queue needs front and rear pointers, and a linked list needs a head pointer plus a free-list pointer for empty spaces.
Question: A stack is empty. Push 5, push 8, pop, push 3, pop, pop. What is popped each time, and what is left on the stack?
Answer: Push 5 → [5]. Push 8 → [5, 8]. Pop → 8 is removed, leaving [5]. Push 3 → [5, 3]. Pop → 3 is removed, leaving [5]. Pop → 5 is removed, leaving the stack empty. The values come out in reverse order of how they went in: 8, then 3, then 5. That is LIFO.
Scores[11] in an array declared [1:10] is an error.This section is for approved SrWL Learning students. Sign in with Google to unlock it — Section 1 is free to read now.
Variables and constants, sequence, selection and iteration, procedures and functions, parameter passing and scope.
Every program is built from three constructs. Sequence is one step after another. Selection chooses a path: IF...THEN...ELSE...ENDIF for two paths, and CASE OF...ENDCASE when one value can take several different paths (such as a menu choice). Iteration repeats steps: a FOR loop repeats a known number of times, a WHILE loop repeats while a condition is true (and may run zero times), and a REPEAT...UNTIL loop always runs at least once and stops when its condition becomes true.
// Count how many marks are passes (50 or more) in an array of 20 marks
Passes ← 0
FOR Index ← 1 TO 20
IF Marks[Index] >= 50 THEN
Passes ← Passes + 1
ENDIF
NEXT Index
OUTPUT "Passes: ", Passes
A procedure carries out a task and returns nothing; a function returns a value. Both take parameters — values passed in when they are called. Parameters can be passed by value (a copy is passed, so changes inside the subprogram do not affect the caller's variable) or by reference (the address is passed, so changes inside the subprogram do change the caller's variable). Use by value when you only need to read the data, and by reference when the subprogram must change it — for example when a sort routine must reorder the caller's array.
Scope is where a variable can be used. A local variable exists only inside the subprogram that declares it; a global variable can be used anywhere in the program. Good programs use local variables wherever possible, because a global variable can be changed by any part of the program, which makes errors hard to find.
# Python: a function that returns a value, and a procedure-like function
def average(marks):
total = 0
for mark in marks:
total = total + mark
return total / len(marks)
scores = [62, 71, 55, 80]
print("Average:", average(scores))
Question: A procedure Double(Number) doubles the value passed to it. If Number is passed by value and the caller passes 7, what is the caller's variable afterwards? What if it is passed by reference?
Answer: By value: the procedure works on a copy, so the caller's variable is still 7 — the doubled value is lost unless the procedure returns it. By reference: the procedure works on the caller's variable itself, so afterwards it holds 14.
← for assignment and use the Cambridge keywords.This section is for approved SrWL Learning students. Sign in with Google to unlock it — Section 1 is free to read now.
The software development life cycle, program design, testing and maintenance.
Building software follows stages: analysis (what is needed), design (how it will work), implementation (writing the code), testing (finding the faults) and maintenance (keeping it working after delivery). The Waterfall model does each stage once, in order — it is simple and easy to manage, but a mistake found late is expensive to fix. The Iterative model builds the system in small versions, improving it each time — feedback comes earlier, but the project can grow without a clear end. Agile works in short cycles with the customer involved throughout — it adapts well to changing requirements, but it needs an experienced team and constant communication.
Before writing code, design it. A structure chart shows the program broken into modules in a tree, with the main module at the top. A state-transition diagram shows the states a system can be in (for example a traffic light: red, red-amber, green, amber) and the events that move it between states. Pseudocode describes the logic of each module in words. Design first, code second — it is far cheaper to fix a design than to rewrite a program.
Stub testing replaces a module that is not written yet with a simple stand-in, so the rest of the program can be tested early. Black-box testing tests what the program does (inputs and outputs) without looking at the code; white-box testing tests the code itself, checking that every path through it runs correctly. Good test data covers three kinds: normal data (ordinary values that should be accepted), boundary data (values at the very edge of what is allowed, such as 0 and 100 for a mark) and erroneous data (values that should be rejected, such as −5 or "abc" for a mark).
After delivery, a program still needs maintenance: corrective (fixing faults found by users), adaptive (changing the program because the world changed — a new law, a new operating system) and perfective (improving it, for example making it faster or adding a feature users asked for).
Question: A program accepts an age from 0 to 120. Give one normal, one boundary and one erroneous test value, and say what should happen for each.
Answer: Normal: 25 — accepted, the program continues. Boundary: 0 and 120 — both accepted, because they are the exact limits; 121 would be rejected. Erroneous: −3 (or "twenty") — rejected with an error message. Boundary values are the ones programmers forget to test, and they are where most errors hide.
Advanced theory and practical programming for Sections 13 to 20, in syllabus order. Each section states what you must be able to do, explains the ideas, and ends with a worked example and exam tips.
This section is for approved SrWL Learning students. Sign in with Google to unlock it — Section 1 is free to read now.
User-defined data types, file organisation and access, floating-point numbers.
Built-in types (INTEGER, REAL, CHAR, STRING, BOOLEAN) are not always enough, so programmers define their own. Composite types combine other types: a record groups different types under one name, a set is a collection of values of the same type with no duplicates, and a class groups data with the methods that work on it. Non-composite types are single values with a restricted set of possibilities: an enumerated type lists every allowed value (for example TYPE Day = (Mon, Tue, Wed, Thu, Fri)), and a pointer type holds the address of another value — pointers are what make dynamic data structures such as linked lists possible.
Files can be organised in three ways. In a serial file, records are stored in the order they arrive, with no sorting. In a sequential file, records are stored in key order, so they must be read from the start to find one. In a random file, each record sits at a position calculated from its key, so any record can be reached directly. Sequential access reads records one after another; direct (random) access jumps straight to the record wanted.
Hashing turns a key into a record address with a hash function — for example, take the key modulo the number of records. A collision happens when two different keys hash to the same address. It is resolved by open addressing (look for the next free space) or chaining (keep a list of all records that share that address).
Very large and very small numbers are stored in floating-point form: a mantissa (the significant digits) and an exponent (how far to move the point). In two's complement floating-point, the mantissa is a two's complement fraction and the exponent is a two's complement integer. A number is normalised when its mantissa starts with 01 (positive) or 10 (negative) — normalisation uses the available bits as well as possible, giving maximum precision.
There is always a trade-off: more bits for the mantissa gives more precision (more significant digits), more bits for the exponent gives more range (bigger and smaller numbers) — you cannot have both with a fixed number of bits. Overflow is when a result is too large to store; underflow is when a result is too small (too close to zero) to store. Rounding error comes from keeping only some digits; truncation error comes from simply cutting off the rest.
Question: A floating-point number uses an 8-bit mantissa and a 4-bit exponent. The value 0.001011 × 23 is not normalised. Normalise it and explain why.
Answer: The mantissa 0.001011 starts with 00, so it is not normalised. Shift the mantissa left until it starts with 01, adjusting the exponent each time: 0.001011 × 23 = 0.01011 × 22 = 0.1011 × 21. The normalised form is mantissa 0.1011 with exponent 1. It uses the same value, but the leading zeros are gone, so the mantissa holds more significant digits — that is the extra precision normalisation gives.
This section is for approved SrWL Learning students. Sign in with Google to unlock it — Section 1 is free to read now.
Protocols and the OSI/TCP-IP models, circuit vs packet switching, peer-to-peer file sharing.
Networks are described in layers, so that each layer only has to talk to the layers next to it. The OSI model has seven layers (physical, data link, network, transport, session, presentation, application); the TCP/IP model has four (network access, internet, transport, application). The exam expects you to know what each layer does in general terms, not to memorise every detail.
| Protocol | What it does |
|---|---|
| IP | Addresses packets and routes them between networks. |
| TCP | Reliable delivery: splits data into packets, numbers them, checks they arrive and resends any that are lost, and puts them back in order. |
| UDP | Fast, connectionless delivery with no checking: packets may arrive out of order or not at all. Used where speed matters more than perfection, such as live video and online games. |
| HTTP / HTTPS | Transfer web pages; HTTPS adds encryption (TLS) so the data cannot be read in transit. |
| FTP | Transfer files between computers. |
| SMTP | Send email from a client to a mail server, and between mail servers. |
| POP3 / IMAP | Receive email: POP3 downloads mail and usually deletes it from the server; IMAP keeps mail on the server so it can be read from many devices. |
TCP is connection-oriented and reliable; UDP is connectionless, fast and unacknowledged. That one sentence answers many comparison questions: choose TCP when every byte must arrive correctly (a file download, a web page), and UDP when a small loss does not matter but delay does (a phone call, a live stream).
Circuit switching reserves a dedicated path for the whole conversation before any data is sent — like an old telephone call. It gives a guaranteed quality but wastes the path when nobody is speaking. Packet switching splits data into packets that travel independently and share the network with other traffic — it uses bandwidth efficiently, but packets can be delayed or arrive out of order.
BitTorrent is peer-to-peer file sharing: a file is split into small pieces, and each computer (peer) downloads pieces from many other peers and uploads the pieces it already has to others. There is no central server holding the file, so the more people downloading, the faster it goes — the opposite of a normal download, where more users slow the server down. A tracker keeps a list of which peers have which pieces.
Question: A student is watching a live football match online. The picture occasionally freezes for a second but then continues. Which protocol is being used, and why is it the right choice?
Answer: UDP. A live stream cannot wait for lost packets to be resent — by the time a retransmission arrived, the moment would have passed. UDP sends the packets as fast as possible and accepts that a few may be lost, which is exactly the brief freeze the student sees. TCP would be wrong here: resending lost packets would delay the stream and make it fall behind the live match.
This section is for approved SrWL Learning students. Sign in with Google to unlock it — Section 1 is free to read now.
RISC and CISC, pipelining, parallel processing, virtual machines, Boolean algebra and logic circuits.
RISC (reduced instruction set) processors have a small set of simple instructions, each taking about one clock cycle, with many registers — they are fast and energy-efficient. CISC (complex instruction set) processors have a large set of instructions, including complex ones that do several things at once, with fewer registers — each instruction is more powerful but takes more cycles. Modern processors often mix both ideas.
Pipelining overlaps the stages of the fetch-decode-execute cycle: while one instruction is being executed, the next is being decoded and the one after that is being fetched — like an assembly line. A pipeline hazard happens when this overlap breaks down, for example when an instruction needs a result that has not been calculated yet, or when a jump changes the flow of instructions; the pipeline must stall (a "bubble") until the problem clears.
Parallel processing uses several processors at once. Flynn's taxonomy describes the four combinations of instruction streams and data streams: SISD (one instruction, one set of data — an ordinary single processor), SIMD (one instruction applied to many sets of data at once — graphics processing), MISD (many instructions on one set of data — rare, used in fault-tolerant systems) and MIMD (many instructions on many sets of data — a cluster of computers, or a multi-core processor). A massively parallel computer links thousands of processors together for very large problems such as weather forecasting.
A virtual machine is a computer simulated in software: a hypervisor runs on the host hardware and lets several guest operating systems run on one physical machine, each believing it has its own computer. Benefits: better use of hardware, easy backup (copy the whole virtual machine), and safe testing. Limitations: each virtual machine shares the physical hardware, so performance is lower than running directly on the machine, and the hypervisor itself needs managing.
De Morgan's laws let you swap between AND and OR with NOT: NOT (A AND B) = (NOT A) OR (NOT B), and NOT (A OR B) = (NOT A) AND (NOT B). They are the main tool for simplifying expressions — and for turning a circuit that needs one kind of gate into a circuit that uses only NAND or only NOR gates.
A half adder adds two single bits: the sum is A XOR B and the carry is A AND B. A full adder adds two bits plus a carry-in, so it can be chained to add whole numbers. A flip-flop is a circuit that remembers one bit: an SR flip-flop sets (S = 1) or resets (R = 1) its output, and a JK flip-flop adds a toggle mode (J = K = 1 flips the output). Flip-flops are the building blocks of registers and memory.
A Karnaugh map (K-map) is a grid for simplifying Boolean expressions visually: the cells are arranged so that neighbouring cells differ in only one variable (Gray code order), and you group adjacent 1s in blocks of 1, 2, 4 or 8. Each group removes one variable from the expression. A 2-variable K-map has 4 cells, a 3-variable map has 8, and a 4-variable map has 16.
Question: Simplify X = NOT (A AND B) and write the result using only OR and NOT.
Answer: By De Morgan's first law, NOT (A AND B) = (NOT A) OR (NOT B). So the circuit needs two NOT gates and one OR gate, and no AND gate at all. Check with a truth table: when A = 1 and B = 1, A AND B = 1 so X = 0; (NOT A) OR (NOT B) = 0 OR 0 = 0. When A = 0 and B = 1, A AND B = 0 so X = 1; (NOT A) OR (NOT B) = 1 OR 0 = 1. The two expressions agree on every row.
This section is for approved SrWL Learning students. Sign in with Google to unlock it — Section 1 is free to read now.
Process scheduling, memory management, the phases of compilation, BNF and syntax diagrams, linkers and loaders.
When several programs want the processor, the operating system's scheduler decides the order. First Come First Served (FCFS) runs jobs in arrival order — simple, but a long job can block everything behind it. Shortest Job First (SJF) runs the quickest job first, which keeps waiting times low, but a long job can be starved. Shortest Remaining Time (SRT) is the preemptive version of SJF: if a shorter job arrives, the current job is paused. Round Robin gives each job a fixed time slice in turn — fair, and good for interactive systems, but switching jobs costs time. Multi-level feedback queues move jobs between queues based on how they behave, giving interactive jobs priority over long background jobs.
Paging divides memory into fixed-size blocks (pages) so a program's pages can be scattered through physical memory; segmentation divides it into variable-size logical units (such as code and data). Virtual memory lets a program use more memory than the computer physically has, by keeping some pages on disk and loading them when needed — a page fault happens when a program needs a page that is on disk, so the operating system must fetch it. Thrashing is when the system spends most of its time swapping pages in and out of disk and almost no time doing useful work — the computer appears to freeze.
Compilation happens in phases. Lexical analysis breaks the source code into tokens (keywords, identifiers, numbers, symbols), throws away comments and whitespace, and builds the symbol table. Syntax analysis (parsing) checks the tokens against the grammar of the language and builds a parse tree — a syntax error is found here. Semantic analysis checks that the program makes sense (for example that a variable has been declared and has the right type). Code generation produces machine code, and optimisation makes it faster or smaller.
A grammar can be written in Backus-Naur Form (BNF), using rules such as <number> ::= <digit> | <digit><number>, or drawn as a syntax diagram with the same information as a picture. A linker joins the compiled code with the libraries it needs; a loader places the finished program into memory so it can run. Libraries can be statically linked (copied into the program when it is built — bigger program, but it runs on its own) or dynamically linked (loaded from a shared file such as a DLL when the program runs — smaller program, but it needs the library file to be present).
Question: Three jobs arrive together. Job A needs 6 ms, Job B needs 3 ms, Job C needs 4 ms. Round Robin uses a time slice of 2 ms. In what order do the jobs finish?
Answer: Slice 1: A runs 2 ms (4 left), B runs 2 ms (1 left), C runs 2 ms (2 left). Slice 2: A runs 2 ms (2 left), B runs 1 ms and finishes (3 ms of work done). C runs 2 ms and finishes. Slice 3: A runs its last 2 ms and finishes. Finish order: B, then C, then A. Round Robin is fair, but B — the shortest job — still had to wait for two slices before it could finish.
::= means "is defined as", | means "or", and angle brackets mark a non-terminal such as <digit>.This section is for approved SrWL Learning students. Sign in with Google to unlock it — Section 1 is free to read now.
Asymmetric encryption, digital signatures, digital certificates and certificate authorities, SSL and TLS.
In symmetric encryption (Section 6) the same key encrypts and decrypts, so the key must be shared safely — and that is the hard part. Asymmetric encryption solves it with a key pair: a public key that anyone may know, and a private key that only its owner knows. Data encrypted with the public key can only be decrypted with the matching private key, so anyone can send you a secret message — but only you can read it. In RSA, the public key is built from the product of two large prime numbers, and the security comes from how hard it is to factor that product back into the two primes.
A digital signature proves who sent a message and that it was not changed. The sender first makes a message digest (a short fingerprint of the message, made with a hash function), then encrypts the digest with their private key — that is the signature. Anyone can decrypt it with the sender's public key and compare it with a fresh digest of the message: if they match, the message is genuine and unchanged. Because only the sender holds the private key, they cannot later deny sending it — this is called non-repudiation.
But how do you know a public key really belongs to the person it claims to? A digital certificate answers that: it is a document containing a person's public key and identity, signed by a trusted certificate authority (CA). Your browser trusts the CA, so it trusts the certificate, so it trusts the public key. If a certificate is stolen or misused, the CA puts it on a revocation list.
When you open a secure website, your browser and the server perform the TLS handshake: the server sends its certificate, the browser checks it, they agree on a session key (using asymmetric encryption to share it safely), and from then on they use fast symmetric encryption for the rest of the session. That is why HTTPS is secure: the handshake uses asymmetric encryption to exchange the key, and symmetric encryption to protect the data.
Question: A teacher sends a signed exam paper to a school. Explain how the school checks the paper is genuine and unchanged, naming the keys used.
Answer: The teacher hashes the paper to make a message digest and encrypts the digest with the teacher's private key — this is the digital signature, sent with the paper. The school decrypts the signature with the teacher's public key (from the teacher's certificate) to recover the original digest, then hashes the paper it received. If the two digests match, the paper came from the teacher and was not altered on the way. If they differ, the paper was changed — or the signature is fake.
This section is for approved SrWL Learning students. Sign in with Google to unlock it — Section 1 is free to read now.
Graphs and trees, A* and Dijkstra search, machine learning, artificial neural networks.
Many AI problems are searches through a graph of possible states — a map of roads, a maze, or the moves in a game. Dijkstra's algorithm finds the shortest path from a start node to every other node by always expanding the node with the smallest known distance so far; it is guaranteed to find the shortest path, but it explores in all directions. A* search is faster because it uses a heuristic — an estimate of the distance still to go. At each step it chooses the node with the smallest f(n) = g(n) + h(n), where g(n) is the cost so far and h(n) is the estimated cost to the goal. A* is still guaranteed to find the shortest path, provided the heuristic never overestimates the true distance.
| Type | What the data looks like | Example |
|---|---|---|
| Supervised learning | Labelled examples: each input comes with the right answer. | Photos labelled "cat" or "dog" teach a model to recognise cats and dogs. |
| Unsupervised learning | No labels: the system finds patterns and groups by itself. | Grouping customers by what they buy, without being told the groups in advance. |
| Reinforcement learning | No right answers at all: the system tries actions and gets rewards or penalties. | A program learning to play a game by winning and losing many times. |
An artificial neural network (ANN) is layers of simple units, loosely modelled on the brain. Each unit takes several inputs, multiplies each by a weight, adds them together with a bias, and passes the result through an activation function that decides whether the unit "fires". The network learns by backpropagation: it compares its output with the right answer, works out how much each weight contributed to the error, and adjusts the weights a little — then repeats this thousands of times over many examples. Training needs a lot of labelled data and a lot of computing power, and the trained network can be hard to explain: it works, but nobody can easily say why it gave a particular answer.
Question: From node S, two neighbours are available: node A with g = 4 and h = 6, and node B with g = 7 and h = 2. Which node does A* expand next, and why?
Answer: Work out f(n) = g(n) + h(n) for each: A has f = 4 + 6 = 10, B has f = 7 + 2 = 9. A* always expands the node with the smallest f, so it expands B next — even though B cost more to reach, its estimated total cost to the goal is lower. That is the point of the heuristic: it guides the search towards the goal instead of wandering in every direction like Dijkstra's algorithm.
This section is for approved SrWL Learning students. Sign in with Google to unlock it — Section 1 is free to read now.
Dynamic abstract data types, tree traversals, insertion sort, recursion.
In Section 10 the ADTs were built from fixed arrays. At A Level they are dynamic: memory is allocated as it is needed, using pointers. A linked list is a chain of nodes, each holding data and a pointer to the next node; a binary tree is a node with at most two children (left and right); a hash table stores values at addresses computed from their keys; a dictionary stores key-value pairs so a value can be found quickly by its key. Pointers manage the links in heap memory, so the structure can grow and shrink — unlike a fixed array, which wastes space when half empty and overflows when full.
Tree traversals visit every node of a binary tree in a fixed order. In-order traversal visits left subtree, then the node, then the right subtree — for a binary search tree this gives the values in sorted order. Pre-order visits the node first, then left, then right (useful for copying a tree). Post-order visits left, then right, then the node (useful for deleting a tree, since children are removed before their parent).
Insertion sort builds the sorted list one item at a time: take the next unsorted item and insert it into its correct place in the sorted part. It is simple and fast on small or nearly-sorted lists, but slow on long random lists. A binary tree search starts at the root and goes left if the value is smaller, right if it is larger, until it finds the value or reaches an empty branch; inserting a value follows the same path and adds a new leaf where the empty branch was.
A recursive routine calls itself to solve a smaller version of the same problem. Every recursive routine needs two parts: a base case that stops the recursion (the simplest version of the problem, with a direct answer) and a recursive step that calls the routine again on a smaller problem. Each call is stored on the call stack until the base case is reached, then the calls return one by one. If the base case is missing or never reached, the calls pile up until the stack overflows and the program crashes.
# Recursive factorial: base case n == 0, recursive step n * factorial(n - 1)
def factorial(n):
if n == 0: # base case
return 1
return n * factorial(n - 1) # recursive step
print(factorial(4)) # 4 * 3 * 2 * 1 * 1 = 24
Question: Trace factorial(3) and show the call stack.
Answer: factorial(3) calls factorial(2), which calls factorial(1), which calls factorial(0). The stack now holds four calls. factorial(0) hits the base case and returns 1. factorial(1) returns 1 × 1 = 1. factorial(2) returns 2 × 1 = 2. factorial(3) returns 3 × 2 = 6. The stack unwinds in reverse order — the last call made is the first to return.
This section is for approved SrWL Learning students. Sign in with Google to unlock it — Section 1 is free to read now.
Programming paradigms, object-oriented programming, low-level programming and declarative programming.
In object-oriented programming (OOP), a class is a blueprint and an object is one instance built from it — a class Student describes what every student has, and each actual student is an object of that class. The data an object holds are its attributes (or properties); the things it can do are its methods. Encapsulation means keeping an object's data hidden inside it and only allowing access through its methods — getters read an attribute and setters change it, so the object can check the new value first.
Inheritance lets a new class take the attributes and methods of an existing class and add its own: a class Teacher can inherit from Person and add a staff number. Polymorphism means the same method name can behave differently in different classes — describe() might print a student's grade for a Student and a teacher's subject for a Teacher — and a program can call it without knowing which kind of object it has. Containment (aggregation) is when one object holds another as part of itself, such as a School holding a list of Students. A constructor runs when an object is created, setting up its starting values.
# A class with a constructor, a method, inheritance and overriding
class Person:
def __init__(self, name):
self.name = name # attribute
def describe(self):
return "Person: " + self.name
class Student(Person): # Student inherits from Person
def __init__(self, name, grade):
super().__init__(name)
self.grade = grade
def describe(self): # overriding: same name, new behaviour
return "Student: " + self.name + ", grade " + self.grade
a = Student("Aung", "A")
print(a.describe()) # Student: Aung, grade A
Low-level programming is assembly language: the same five addressing modes from Section 4 (immediate, direct, indirect, indexed, relative) and the same idea that every instruction is an op-code plus an operand. Imperative (procedural) programming is the style of Sections 11 and 19: the programmer writes the steps, in order, using variables, constructs, procedures and functions.
Declarative programming is different: instead of writing steps, you write facts and rules, and the system works out how to answer a question from them. For example, facts: parent(thiri, aung) and parent(aung, may); rule: grandparent(X, Z) IF parent(X, Y) AND parent(Y, Z). Ask "who is May's grandparent?" and the system uses the rule to answer "Thiri" — you never wrote the steps to search. Note that Paper 4 does not assess low-level or declarative programming; they are examined in Paper 3.
Question: A school system needs to store students and teachers. Both have a name and an email; students have a grade, teachers have a subject. Design the classes and explain how inheritance helps.
Answer: Create a base class Person with attributes name and email and a method describe(). Create Student inheriting from Person, adding grade; and Teacher inheriting from Person, adding subject. Inheritance helps because name, email and the basic describe() are written once in Person instead of twice — if the school later adds a phone number, it is added in one place only. Each subclass can override describe() to include its own extra information.