IGCSE Computer Science Paper 1 & Paper 2
Detailed theory notes, Python and pseudocode, and a mind map for every one of the ten chapters. Log in with the class password to open them.
Cambridge 0478 · Notes by Tr. Wai Lin Htet
How a computer sees a number
Tap the bits. Turn them on and off and watch the value change.
- Denary
- 65
- Hex
- 41
- ASCII character
- A
Chapter list
Ten chapters across two exam papers. Pick any chapter to jump straight to it once you are logged in.
Paper 2 · Algorithms, Programming & Logic
Mind maps for chapters 1 to 10
One-page visual summaries for last-minute revision. Chapters 2, 7, 8, 9 and 10 have two maps each.
Paper 1 · Computer Systems
Theory notes for chapters 1 to 6. Each chapter follows the syllabus order and ends with the mistakes examiners see most often.
Data Representation
How computers store numbers, text, sound and images as binary, and how files are made smaller.
1.1Number systems
A computer is built from billions of tiny switches called transistors. Each switch is either off or on, so the natural way to store anything is as a pattern of two states: 0 and 1. That is why every kind of data (numbers, letters, pictures, music, program instructions) is stored as binary.
| System | Base | Digits used | Where you meet it |
|---|---|---|---|
| Denary (decimal) | 10 | 0–9 | Everyday counting and maths |
| Binary | 2 | 0, 1 | Inside every processor and memory chip |
| Hexadecimal | 16 | 0–9, A–F | Colour codes, MAC addresses, memory addresses, error codes |
Binary to denary
Each bit has a place value that doubles as you move left. Add up the place values where the bit is 1.
| 128 | 64 | 32 | 16 | 8 | 4 | 2 | 1 |
|---|---|---|---|---|---|---|---|
| 1 | 0 | 0 | 1 | 1 | 1 | 0 | 0 |
128 + 16 + 8 + 4 = 156. To go the other way, subtract place values from the largest downwards: 156 − 128 = 28, then 28 − 16 = 12, 12 − 8 = 4, 4 − 4 = 0, which gives 10011100.
Binary and hexadecimal
One hex digit represents exactly four bits (a nibble), so conversion is a matter of splitting into groups of four. Hex letters: A = 10, B = 11, C = 12, D = 13, E = 14, F = 15.
1001 1100 → 9 and C → 9C. In the other direction, 2B → 0010 and 1011 → 00101011 = 43.
Try it: converter
Type in any box (0 to 255). The other two update.
- It is much shorter than binary (8 bits become 2 characters).
- It is easier for people to read, remember and copy without mistakes.
- It converts to and from binary quickly, so it is a convenient shorthand, not a different way for the computer to store data.
Binary addition and overflow
Rules for each column, working right to left: 0 + 0 = 0; 0 + 1 = 1; 1 + 1 = 0 carry 1; 1 + 1 + 1 = 1 carry 1.
10110110 (182) + 01101011 (107) ---------- 100100001 (289) ← 9 bits Register holds 8 bits, so the left-hand 1 is lost: 00100001 (33) → OVERFLOW ERROR
Overflow happens when the result is too big for the number of bits available. In 8 bits the largest value is 255, so anything above 255 overflows and the answer stored is wrong.
Logical shifts
A logical shift moves every bit left or right by a number of places. Bits that fall off the end are lost, and the gaps are filled with 0.
- Left shift by 1 multiplies by 2.
00001101(13) shifted left 2 places gives00110100(52). - Right shift by 1 divides by 2 (whole number).
10110100(180) shifted right 3 places gives00010110(22). The three bits100that fell off were lost, which is why 180 ÷ 8 = 22.5 became 22. - Shifting can cause loss of precision or overflow if a 1 falls off the left end.
Two's complement (negative numbers)
The left-most bit has the value −128 instead of +128. Numbers with a leading 1 are negative. The range of 8-bit two's complement is −128 to +127.
- Write the positive number in binary: 45 =
00101101. - Invert every bit:
11010010. - Add 1:
11010011.
Check: −128 + 64 + 16 + 2 + 1 = −45.
- Forgetting to write all 8 bits (leading zeros matter in a register).
- Saying hexadecimal is "used by computers". Computers use binary; hex is for humans.
- Forgetting to add 1 in two's complement.
1.2Text, sound and images
Text
Every character is given a number in a character set, and that number is stored in binary. Letters follow in order, so once you know 'A' = 65 you know 'B' = 66; lower-case 'a' = 97; the digit character '0' = 48.
| ASCII | Unicode | |
|---|---|---|
| Bits per character | 7 bits (128 characters); extended ASCII uses 8 bits (256) | Up to 32 bits (UTF-8, UTF-16, UTF-32) |
| Characters covered | English letters, digits, punctuation, control codes | Almost every language, symbols and emoji, including Myanmar script |
| File size | Smaller | Larger for the same number of characters |
Sound
Real sound is analogue (a continuous wave). To store it, the wave is measured at regular intervals; this is called sampling. Each measurement is stored as a binary number.
- Sample rate
- Number of samples taken each second, in hertz (Hz). CD audio uses 44,100 Hz.
- Sample resolution
- Number of bits used for each sample (bit depth). CD audio uses 16 bits.
Raising either value makes the stored sound a closer match to the original wave, but the file becomes larger.
Images
An image is a grid of tiny squares called pixels. Each pixel stores a binary number that represents its colour.
- Resolution
- Width × height in pixels. More pixels means more detail and a larger file.
- Colour depth
- Bits per pixel. 1 bit = 2 colours, 8 bits = 256 colours, 24 bits = about 16.7 million colours.
Metadata is data about the file, such as the image width, height and colour depth, or the sound file's sample rate and length. The computer needs it to rebuild the file correctly.
1.3Data storage and compression
| Unit | Size |
|---|---|
| Bit | A single 0 or 1 |
| Nibble | 4 bits |
| Byte | 8 bits |
| Kibibyte (KiB) | 1024 bytes |
| Mebibyte (MiB) | 1024 KiB |
| Gibibyte (GiB) | 1024 MiB |
| Tebibyte (TiB) | 1024 GiB |
| Pebibyte (PiB) | 1024 TiB |
File size formulas
Image size (bits) = width × height × colour depth Sound size (bits) = sample rate × sample resolution × length in seconds Bytes = bits ÷ 8 KiB = bytes ÷ 1024 MiB = KiB ÷ 1024
Compression
Compression reduces file size, so files use less storage, take less bandwidth and transfer faster.
| Lossless | Lossy | |
|---|---|---|
| Original data | Can be rebuilt exactly | Some data permanently removed |
| File size reduction | Smaller | Much smaller |
| Examples | PNG, FLAC, ZIP, run-length encoding (RLE) | JPEG, MP3, MP4 |
| Methods | Replace repeated data with a short code | Reduce resolution, colour depth or sample rate; drop detail people barely notice |
| Best for | Text, program files, medical images | Photos, music and video on the web |
Run-length encoding: store each value once with a count of how many times it repeats. AAAABBBCC becomes 4A3B2C (9 characters shrink to 6). It works best on data with long runs, such as simple graphics.
Data Transmission
How data travels between devices, how errors are caught, and how encryption keeps it private.
2.1Types and methods of transmission
Packets
Data sent over a network is split into small units called packets. Each packet has three parts:
- Header
- Destination IP address, sender's IP address, packet number (so they can be put back in order), and the number of packets.
- Payload
- The actual piece of data being carried.
- Trailer
- Marks the end of the packet and usually holds an error-checking value.
Packet switching
- The message is broken into packets, each numbered.
- Each packet is sent separately. Routers read the header and choose the best route at that moment, so packets may take different routes.
- Packets can arrive out of order. The receiving device uses the packet numbers to reassemble them.
- If a packet is missing or damaged, the receiver asks for it to be sent again.
Advantages: no single route is tied up, so the network is used efficiently; if one route fails, packets take another; it is harder to intercept a whole message. Disadvantages: packets may arrive late or out of order, and reassembly takes time (which can hurt live audio or video).
Serial and parallel
| Serial | Parallel | |
|---|---|---|
| How | One bit at a time along one wire | Several bits at once along several wires |
| Good for | Long distances; reliable; cheaper cabling | Short distances, such as inside a computer |
| Weakness | Slower for the same clock speed | Bits can arrive at slightly different times (skew) and wires interfere with each other, worse over long cables |
Direction of transmission
| Type | Direction | Example |
|---|---|---|
| Simplex | One direction only | Keyboard to computer, TV broadcast |
| Half-duplex | Both directions, but only one at a time | Walkie-talkie |
| Full-duplex | Both directions at the same time | Phone call, broadband connection |
Universal Serial Bus (USB)
USB sends data serially. Advantages: one standard connector on most devices; plug-and-play (the computer detects the device); can supply power; backwards compatible with older versions; USB-C plugs in either way round. Drawbacks: limited cable length; a lower maximum speed than some specialised connections; older versions are slower.
2.2Methods of error detection
Errors happen during transmission because of interference, electrical noise or a weak signal. Data can be lost, gained (extra bits) or changed (a 0 becomes a 1). Detection methods find out that something has gone wrong; they do not fix it.
Parity check
The sender and receiver agree on even or odd parity. One extra bit (the parity bit) is added so the total number of 1s is even (or odd). The receiver counts the 1s; if the count is wrong, an error occurred.
Example (even parity): 1011001 has four 1s, which is already even, so the parity bit is 0. 1011011 has five 1s, so the parity bit is 1.
Parity block (parity byte) check: the data is arranged in rows and columns and a parity bit is added for every row and every column. A single wrong bit is located where the failing row and column meet.
Checksum
A value is calculated from the data using an agreed algorithm and sent with the data. The receiver repeats the calculation. If the results differ, the data is corrupt and is sent again.
Echo check
The receiver sends a copy of the data it received back to the sender, who compares it with the original. If they differ, the data is sent again. It is not efficient because it doubles the traffic, and an error could have happened on the return trip instead.
Check digit
An extra digit at the end of a number (such as an ISBN or barcode) is calculated from the other digits. When the number is typed or scanned, the digit is recalculated. It catches data-entry mistakes such as a wrong digit or two digits swapped.
Automatic repeat query (ARQ)
- The receiver checks each packet for errors.
- If it is correct, a positive acknowledgement is sent. If not, a negative acknowledgement asks for it again.
- The sender starts a timeout. If no acknowledgement arrives in time, it resends the packet.
- This repeats until the packet is acknowledged, or a set number of attempts is reached.
2.3Encryption
Encryption scrambles data (plaintext) into unreadable ciphertext using an algorithm and a key. It does not stop data being intercepted; it makes intercepted data useless without the key.
| Symmetric | Asymmetric | |
|---|---|---|
| Keys | One secret key used to encrypt and decrypt | A key pair: public key encrypts, private key decrypts |
| Main problem | The key has to be shared, and could be stolen on the way | Slower, but the private key is never sent to anyone |
| Used for | Encrypting large amounts of data | Exchanging keys safely, for example in HTTPS (SSL/TLS) |
To send a secret message to someone with asymmetric encryption, you encrypt with their public key. Only their private key can decrypt it.
Hardware
What is inside the CPU, how instructions are run, and the devices that go in and out of a computer.
3.1Computer architecture
The central processing unit (CPU) processes data and instructions. The Von Neumann architecture stores both program instructions and data in the same main memory (RAM) and fetches them one after another.
- Arithmetic logic unit (ALU)
- Carries out calculations and logical comparisons.
- Control unit (CU)
- Fetches and decodes instructions and sends control signals to coordinate the rest of the computer.
- Program counter (PC)
- Holds the address of the next instruction.
- Memory address register (MAR)
- Holds the address of the memory location to be read from or written to.
- Memory data register (MDR)
- Holds data or the instruction just fetched from memory, or about to be written to it.
- Current instruction register (CIR)
- Holds the instruction being decoded and executed.
- Accumulator (ACC)
- Holds the results of ALU calculations.
Buses
| Bus | Carries | Direction |
|---|---|---|
| Address bus | Memory addresses | One way, from the CPU to memory |
| Data bus | Data and instructions | Both ways |
| Control bus | Control signals such as read, write and clock | Both ways |
The fetch–decode–execute cycle
- The address in the PC is copied to the MAR.
- The PC is increased by 1, ready for the next instruction.
- The instruction at that address is fetched from RAM along the data bus into the MDR.
- The instruction is copied from the MDR to the CIR.
- The CU decodes the instruction.
- The instruction is executed (the ALU does any calculation, with results held in the ACC). The cycle then starts again.
What affects CPU performance
| Factor | Effect |
|---|---|
| Clock speed | Cycles per second (GHz). A higher speed means more instructions per second, but also more heat. |
| Number of cores | Each core runs its own instructions, so more cores can share the work. Gains are smaller if software cannot split tasks up. |
| Cache size | Cache is very fast memory close to the CPU. More cache means fewer slow trips to RAM. |
The instruction set is the list of machine-code commands a given CPU can carry out. An embedded system is a computer built into a device to do one dedicated job, such as a washing machine controller, a microwave, traffic lights or a car engine unit. A general-purpose computer, by contrast, can run many different programs.
3.2Input and output devices
An input device sends data into the computer; an output device sends data or results out.
| Device | How it works / key point |
|---|---|
| Resistive touchscreen | Two flexible layers pressed together at the touch point. Cheap; works with a gloved finger or stylus; not multi-touch friendly. |
| Capacitive touchscreen | Detects the electrical charge of a finger. Supports multi-touch; does not respond to plain gloves. |
| Infra-red touchscreen | A grid of infra-red beams; a touch breaks the beams. |
| Barcode / QR reader | Shines light at the code and reads the pattern of dark and light stripes or squares. |
| Scanner (2D and 3D) | 2D copies a flat document into an image; 3D captures the shape of an object. |
| Digital camera, microphone | Convert light or sound into digital data. |
| LCD / LED screen | Liquid crystals let light from a backlight (LED) through each pixel to make colour. |
| Inkjet printer | Sprays tiny droplets of ink from nozzles. Good photo quality, lower cost to buy. |
| Laser printer | A laser draws the page on a charged drum, which picks up toner and transfers it to paper, then heat fuses it. Fast and cheap per page. |
| 3D printer | Builds an object layer by layer from plastic, resin or powder. |
| Actuators | Output devices that cause movement or action, for example motors, pumps, heaters and buzzers. |
Sensors
A sensor measures a physical quantity and turns it into a signal the computer can use. Know the common types and one use for each:
| Sensor | Example use |
|---|---|
| Temperature | Greenhouse, oven, central heating |
| Light | Automatic street lights, camera exposure |
| Moisture / humidity | Watering crops, weather stations |
| Pressure | Burglar alarm mat, tyre monitoring |
| Infra-red / motion | Security lights, automatic doors |
| Acoustic (sound) | Glass-break alarm |
| Gas, pH, level, flow, magnetic field, proximity, accelerometer | Factories, water treatment, phones and cars |
3.3Data storage
| RAM | ROM | |
|---|---|---|
| Full name | Random access memory | Read-only memory |
| Volatile? | Yes: contents lost when power is off | No: contents kept |
| Read/write | Read and write | Read only |
| Holds | Programs, data and parts of the OS in use | Start-up instructions (bootloader / BIOS) |
Primary storage is directly accessed by the CPU (RAM, ROM). Secondary storage is non-volatile and keeps files long-term; the CPU cannot access it directly.
| Type | How it works | Strengths | Weaknesses |
|---|---|---|---|
| Magnetic (hard disk drive) | Spinning platters divided into magnetised areas, read and written by a moving head | Large capacity, low cost per GB | Moving parts: slower, noisy, can break if dropped, uses more power |
| Optical (CD, DVD, Blu-ray) | A laser reads pits and lands on a spinning disc. Blu-ray's blue laser has a shorter wavelength so it fits more data. | Cheap, light, easy to post | Low capacity, slower, scratches easily |
| Solid state (SSD, USB flash, SD card) | Flash memory: transistors trap electric charge to represent 0 and 1; no moving parts | Very fast, silent, low power, durable | More expensive per GB; a limited number of write cycles |
Virtual memory
If RAM fills up, the operating system moves sections of data that are not currently needed (pages) out to a reserved area of secondary storage, and brings them back when needed. This lets the computer run more programs than RAM alone can hold, but secondary storage is much slower than RAM, so too much paging makes the computer sluggish.
Cloud storage
Data is stored on remote servers and accessed over the internet. Benefits: reachable from any device, automatic backup, easy to add space. Drawbacks: needs an internet connection, ongoing subscription cost, you rely on the provider's security and reliability.
3.4Network hardware
- Network interface card (NIC)
- Allows a device to connect to a network, wired or wireless. It stores the device's MAC address.
- Router
- Connects networks together (for example your home LAN to the internet). It reads each packet's destination IP address and forwards it, and it gives IP addresses to devices on the local network.
| MAC address | IP address | |
|---|---|---|
| Assigned by | Manufacturer, when the NIC is made | The network (router or ISP) |
| Changes? | Fixed to the hardware | Can change depending on the network |
| Format | 48 bits, written as six hex pairs, e.g. 00:1A:2B:3C:4D:5E. First half identifies the manufacturer. | IPv4: four numbers 0–255, e.g. 192.168.0.1 (32 bits). IPv6: eight groups of hex (128 bits). |
| Purpose | Identifies the physical device on a local network | Identifies where a device is on a network, so packets can be routed |
IPv6 exists because the world is running out of IPv4 addresses. An IP address can be static (never changes, used for servers) or dynamic (a new one is given each time a device connects, which is the norm at home).
Software
System and application software, what an operating system does, interrupts, and how code is translated.
4.1Types of software and interrupts
| System software | Application software | |
|---|---|---|
| Purpose | Runs and maintains the computer itself | Lets the user do a task |
| Examples | Operating system, utility programs, device drivers | Word processor, web browser, spreadsheet, game |
What an operating system does
- User interface: a GUI (icons, windows) or a command-line interface.
- Memory management: decides which programs use which part of RAM and controls virtual memory.
- Process management and multitasking: shares CPU time so several programs appear to run at once.
- File management: creates, names, moves, copies and deletes files and folders.
- Peripheral management: controls input and output devices, using device drivers.
- Security: user accounts, passwords and access rights.
- Providing a platform on which application software can run.
Utility software and drivers
Utilities are small programs that maintain the computer: antivirus, backup, disk formatting, defragmentation (only useful on hard disks, not SSDs), file compression and disk clean-up. A device driver tells the OS how to communicate with one particular piece of hardware such as a printer.
Interrupts
An interrupt is a signal sent to the processor asking it to stop what it is doing because something needs attention.
| Type | Source | Examples |
|---|---|---|
| Hardware | A device | Key pressed, mouse clicked, printer out of paper, disk transfer finished |
| Software | A running program | Division by zero, invalid instruction, two programs trying to use the same memory |
- An interrupt signal is generated.
- At the end of each fetch–decode–execute cycle the CPU checks for interrupts.
- If the interrupt has a higher priority than the current task, the CPU saves the current state (register contents).
- The interrupt service routine (ISR) for that interrupt is run.
- The saved state is restored and the interrupted task carries on.
4.2Languages, translators and IDEs
| High-level language | Low-level language | |
|---|---|---|
| Examples | Python, Java, C#, Visual Basic | Machine code (binary), assembly language |
| Readability | English-like, easier to read, write and debug | Hard to read; assembly uses short mnemonics such as ADD, LDA |
| Portability | Runs on many machines after translation | Tied to one type of processor |
| Hardware control | Less direct | Direct control, memory and speed efficient |
| Translation needed | Compiler or interpreter | Assembly needs an assembler; machine code runs as it is |
| Compiler | Interpreter | |
|---|---|---|
| How it translates | Whole program at once into an executable file | One line at a time, and runs it straight away |
| Errors | Listed after the whole program is checked | Stops at the first error |
| Speed of running | Fast, because translation is already done | Slower; translation happens every run |
| Source code needed? | Not once compiled, so it can be sold without the code | Yes, every time it runs |
| Best for | Finished programs | Development and testing |
An assembler translates assembly language into machine code.
Integrated development environment (IDE)
An IDE bundles the tools a programmer needs into one program:
- Code editor with syntax highlighting, auto-completion, auto-indentation and pretty-printing.
- Error diagnostics to point out mistakes and a debugger with breakpoints, single-stepping and variable watches.
- A built-in translator (compiler or interpreter) and a run-time environment to test the program.
The Internet and its Uses
The web, how a page reaches you, digital money, and the threats that put users at risk.
5.1The internet and the World Wide Web
| The internet | The World Wide Web (WWW) |
|---|---|
| The worldwide network of connected networks: the infrastructure of cables, routers and servers. | A collection of web pages and websites written in HTML and accessed with a browser over the internet. It is one service that runs on the internet (email is another). |
URL structure
https://www.example.com/school/index.html └─┬─┘ └──────┬──────┘└────┬────┘└───┬────┘ protocol domain name path file name
The web browser reads the HTML and displays the page. The web server stores the pages and sends them when requested.
What happens when you type a URL
- The browser asks a DNS server for the IP address of the domain name.
- If that server does not know it, it asks other DNS servers until the IP address is found and returned.
- The browser sends a request to the web server at that IP address.
- The web server sends back the page (as HTML), and the browser renders it.
HTTP and HTTPS
HTTP is the protocol for sending web pages, but the data is not encrypted. HTTPS adds SSL/TLS: the browser checks the server's digital certificate, they agree a session key using asymmetric encryption, and all data after that is encrypted. A padlock icon shows HTTPS is in use.
Cookies
A cookie is a small text file stored by the browser when you visit a site.
- Session cookies are held in memory and deleted when the browser closes (for example a shopping basket or keeping you logged in during a visit).
- Persistent cookies stay on the device until they expire or are deleted (remembering login details, language and preferences, or tracking browsing to target adverts).
5.2Digital currency
Digital currency exists only in electronic form. Cryptocurrencies are decentralised: there is no bank in control.
A blockchain is the digital ledger that records every transaction:
- Transactions are grouped into blocks. Each block stores its data, a timestamp, its own hash and the hash of the previous block, so the blocks form a chain.
- If someone changes a block, its hash changes and no longer matches the next block. The chain is broken and the tampering is obvious.
- Many computers hold a copy of the ledger and agree on new blocks together, so there is no single point to attack.
Benefits include fast transfers and no bank fees. Drawbacks include price swings, high energy use for some systems, no way to recover lost keys, and use in scams.
5.3Cyber security
| Threat | What it is | How to reduce it |
|---|---|---|
| Brute-force attack | Software tries every possible password until one works | Long, complex passwords; limit login attempts; two-factor authentication |
| Data interception | Data is captured in transit (for example with a packet sniffer) | Encryption, HTTPS |
| Distributed denial of service (DDoS) | Many computers (a botnet) flood a server with requests so real users cannot get through | Firewall, proxy server, traffic monitoring |
| Hacking | Gaining unauthorised access to a system or data | Firewall, strong passwords, biometrics, software updates |
| Phishing | Fake emails or messages that lead you to a fake site to steal details | Check the sender and links; spam filters; never enter details from links in messages |
| Pharming | Malicious code redirects you to a fake site even when you type the right address | Anti-malware; check the URL and padlock |
| Social engineering | Tricking people into giving up information or access | Staff training and verification procedures |
Malware
| Type | Behaviour |
|---|---|
| Virus | Attaches itself to a file and spreads when that file is opened; can delete or corrupt data |
| Worm | Copies itself across networks without needing a user to open anything |
| Trojan horse | Looks like useful software but carries harmful code; needs the user to install it |
| Spyware | Secretly records what you do (such as key presses) and sends it away |
| Adware | Floods you with unwanted adverts and may track browsing |
| Ransomware | Encrypts your files and demands payment for the key |
Protection methods
- Firewall
- Checks incoming and outgoing traffic against a set of rules and blocks anything unauthorised.
- Anti-malware
- Scans for, quarantines and removes malicious software; keep it updated.
- Authentication
- Passwords, biometrics (fingerprint, face, iris, voice) and two-factor authentication (two different proofs, such as a password plus a code sent to a phone).
- Proxy server
- Sits between users and the internet. It can filter websites, cache pages and hide users' IP addresses.
- Access levels
- Users only see the data they need for their role.
- Software updates
- Fix known security holes; turn on automatic updates.
Automated & Emerging Technologies
Systems that sense and act on their own, robots, and artificial intelligence.
6.1Automated systems
An automated system uses sensors, a microprocessor and actuators to run a process with little or no human help. It works as a feedback loop:
- Sensors measure a physical value (for example temperature).
- If the signal is analogue, an analogue-to-digital converter (ADC) turns it into digital data.
- The microprocessor compares the reading with a stored target value.
- If action is needed, it sends a signal (through a digital-to-analogue converter, DAC, if required) to an actuator such as a heater or motor.
- The sensor keeps measuring, so the result of the action feeds back in. The loop repeats.
Other examples: automatic street lighting, central heating, automatic doors, air-conditioning, self-driving vehicles, farm drones and factory production lines.
| Advantages | Disadvantages |
|---|---|
| Works 24 hours a day without tiring; no human error; consistent results; can work in dangerous places; cheaper to run in the long term | High cost to set up and maintain; jobs may be lost; skills are lost; if it fails, the whole process may stop; can be hacked |
6.2Robotics and artificial intelligence
Robotics
A robot is a machine with a mechanical structure, electrical parts (sensors, motors and a controller) and a program that lets it carry out tasks. Uses: welding and painting in factories, exploring places people cannot go, surgery, vacuum cleaning, warehouse picking and farming.
Benefits: precise, tireless, safe in hazardous places. Drawbacks: expensive, can replace workers, cannot adapt to situations they were not programmed for.
Artificial intelligence (AI)
AI is a computer system that carries out tasks normally needing human intelligence, such as learning, reasoning, problem solving and recognising speech or images.
Machine learning is a part of AI in which a system improves at a task by learning from data instead of being told every rule. It is used in recommendations, spam filters and voice assistants.
Expert systems
An expert system imitates a human specialist to give advice or a diagnosis. It has four main parts:
- Knowledge base
- A large database of facts about the subject.
- Rule base
- IF…THEN rules that link facts to conclusions.
- Inference engine
- The reasoning part. It applies the rules to the knowledge base and the user's answers to reach a conclusion.
- User interface
- Lets the user answer questions and read the results, often with an explanation of how the conclusion was reached.
Uses: medical diagnosis, finding faults in car engines, mineral prospecting, financial advice, chess.
Paper 2 · Algorithms, Programming & Logic
Chapters 7 to 10: the twelve essentials of algorithm design, Python and pseudocode side by side, databases with SQL, and logic gates.
Algorithm Design & Problem-solving
The twelve essentials, in the order they usually appear in the exam. Pseudocode is shown with Cambridge conventions; Python is shown where you will be asked to code.
1Program development life cycle (SDLC)
Programs are built in stages, so that mistakes are found early when they are cheap to fix.
| Stage | What happens |
|---|---|
| Analysis | Find out exactly what the program must do. Abstraction (keep only the important details) and decomposition (break the problem into smaller parts). List the inputs, processes, outputs and any data to store, using interviews, questionnaires and observation. |
| Design | Plan the solution before coding: structure diagrams, flowcharts and pseudocode. Decide the data structures and validation, and how the screens will look. |
| Coding | Write the program in a programming language, following the design. Test each part as it is written. |
| Testing | Run the program with test data to find and fix errors, and check it does everything the requirements ask for. |
2A program: input, process, output
Every program takes input, applies a process and produces output. Storage (files and databases) keeps data between runs. Designs are drawn as flowcharts or structure diagrams.
Flowchart symbols
| Symbol | Meaning |
|---|---|
| Rounded box (terminator) | START or STOP |
| Parallelogram | Input or output |
| Rectangle | Process, such as a calculation or assignment |
| Diamond | Decision, with two exits labelled Yes and No |
| Rectangle with double side lines | Predefined process (a procedure or function defined elsewhere) |
| Arrows | Direction of flow |
Structure diagram
A structure diagram breaks a system into sub-systems, from the overall task at the top down to small jobs at the bottom (top-down design). It shows what the parts are, not the order they run in.
- Library system
- Members
- Register member
- Update details
- Books
- Add book
- Search for book
- Loans
- Issue book
- Return book
- Calculate fine
- Members
3Data types
| Cambridge pseudocode | Python | Stores | Example |
|---|---|---|---|
| INTEGER | int | Whole numbers | 42, −7 |
| REAL | float | Numbers with a decimal part | 3.14, −0.5 |
| CHAR | str (length 1) | A single character | 'A' |
| STRING | str | Text of any length | "Hello" |
| BOOLEAN | bool | True or False only | TRUE |
4Operators
| Type | Pseudocode | Python | Meaning |
|---|---|---|---|
| Arithmetic | + − * / | + − * / | Add, subtract, multiply, divide (result can be a decimal) |
| ^ | ** | Power: 2 ^ 3 = 8 | |
| DIV | // | Whole-number division: 17 DIV 5 = 3 | |
| MOD | % | Remainder: 17 MOD 5 = 2. MOD 2 = 0 tests for even. | |
| Comparison | = <> < > <= >= | == != < > <= >= | Equal, not equal, less than, greater than, and so on. Result is TRUE or FALSE. |
| Logical | AND OR NOT | and or not | Combine conditions. AND needs both true; OR needs at least one; NOT reverses. |
= assigns a value and == compares. In Cambridge pseudocode, assignment is ← and comparison is =.5Variables and constants
A variable is a named memory location whose value can change while the program runs (a score, a counter, a total). A constant is a named value that does not change (VAT rate, pi, maximum class size). Use meaningful names, and use constants so a value only needs changing in one place.
DECLARE Score : INTEGER CONSTANT VATRate ← 0.2 Score ← 0 Score ← Score + 10
VAT_RATE = 0.2 # constant by convention (capitals) score = 0 score = score + 10
6Selection
Selection lets the program choose which statements to run, depending on a condition.
INPUT Mark
IF Mark >= 70 THEN
OUTPUT "Distinction"
ELSE
IF Mark >= 40 THEN
OUTPUT "Pass"
ELSE
OUTPUT "Fail"
ENDIF
ENDIF
mark = int(input("Mark: "))
if mark >= 70:
print("Distinction")
elif mark >= 40:
print("Pass")
else:
print("Fail")
When one variable is compared with many fixed values, use CASE OF (Python 3.10+: match):
CASE OF Choice 1 : OUTPUT "Start game" 2 : OUTPUT "Options" OTHERWISE : OUTPUT "Invalid choice" ENDCASE
7Iteration (loops)
| Loop | Use when | Condition tested | Runs at least once? |
|---|---|---|---|
| FOR … TO … NEXT | The number of repeats is known | Counter reaches its end value | Yes (if start ≤ end) |
| REPEAT … UNTIL | Repeat until something becomes true | At the end; stops when TRUE | Always |
| WHILE … DO … ENDWHILE | Repeat while something is true | At the start; continues while TRUE | Not necessarily: may run zero times |
FOR Count ← 1 TO 5 OUTPUT Count NEXT Count REPEAT INPUT Password UNTIL Password = "cs0478" WHILE Lives > 0 DO PlayRound ENDWHILE
for count in range(1, 6): # 1 to 5
print(count)
while True: # REPEAT-UNTIL pattern
password = input("Password: ")
if password == "cs0478":
break
while lives > 0:
play_round()
range(1, 6) stops before 6. Python has no REPEAT…UNTIL; the while True … break pattern above does the same job.8Maximum, minimum, counting and totalling
These four standard algorithms appear in almost every Paper 2 question. Start the total and count at 0, and start the max and min at the first value, not at 0.
Total ← 0
Count ← 0
Highest ← Marks[1]
Lowest ← Marks[1]
FOR Index ← 1 TO 5
Total ← Total + Marks[Index]
Count ← Count + 1
IF Marks[Index] > Highest THEN
Highest ← Marks[Index]
ENDIF
IF Marks[Index] < Lowest THEN
Lowest ← Marks[Index]
ENDIF
NEXT Index
Average ← Total / Count
marks = [72, 85, 60, 91, 55]
total = 0
count = 0
highest = marks[0]
lowest = marks[0]
for m in marks:
total = total + m
count = count + 1
if m > highest:
highest = m
if m < lowest:
lowest = m
average = total / count
Result for this data: total 363, count 5, highest 91, lowest 55, average 72.6.
9Lists and one-dimensional arrays
An array stores several items of the same data type under one name. Each item is reached by its index. A Python list written [item1, item2, …] is used for arrays. Two-dimensional arrays (rows and columns) are covered in Chapter 8.
DECLARE Names : ARRAY[1:3] OF STRING Names[1] ← "Aung" Names[2] ← "Su" Names[3] ← "Zin" FOR Index ← 1 TO 3 OUTPUT Names[Index] NEXT Index
names = ["Aung", "Su", "Zin"]
print(names[0]) # Aung
names[1] = "Mya" # change an item
names.append("Kyaw") # add to the end
for i in range(len(names)):
print(names[i])
ARRAY[1:3]). Python lists always start at index 0, so the last item of a 5-item list is list[4].10Linear search and bubble sort
Linear search
Check each item in turn from the start until the target is found or the end is reached. It works on unsorted data, but is slow on long lists because in the worst case every item is checked.
Found ← FALSE
Index ← 1
WHILE Index <= 5 AND Found = FALSE
IF Data[Index] = Target THEN
Found ← TRUE
ELSE
Index ← Index + 1
ENDIF
ENDWHILE
IF Found THEN
OUTPUT "Found at ", Index
ELSE
OUTPUT "Not found"
ENDIF
found = False
index = 0
while index < len(data) and not found:
if data[index] == target:
found = True
else:
index = index + 1
if found:
print("Found at", index)
else:
print("Not found")
Bubble sort
Compare each pair of neighbouring items and swap them if they are in the wrong order. After each pass the largest unsorted value has "bubbled" to the end. Keep going until a full pass makes no swaps.
n = len(data)
for i in range(n - 1):
swapped = False
for j in range(n - 1 - i):
if data[j] > data[j + 1]:
temp = data[j]
data[j] = data[j + 1]
data[j + 1] = temp
swapped = True
if not swapped:
break
Try it: bubble sort, one step at a time
Enter numbers separated by commas (up to 10). The highlighted pair is being compared, red cells were just swapped, green cells are in their final place.
11Validation and verification
Validation is an automatic check that data is reasonable (sensible and in the right form). It cannot prove the data is correct: a date of birth of 01/01/2000 passes even if the real date is 05/03/2000. Verification checks that the data entered is the same as the source data or was not changed in transfer.
| Validation check | What it does | Example |
|---|---|---|
| Range check | Value is between a minimum and maximum | Mark between 0 and 100 |
| Length check | Correct number of characters | Password at least 8 characters |
| Type check | Correct data type | Age must be a whole number |
| Presence check | Field is not left empty | Surname required |
| Format check | Follows a set pattern | Date as DD/MM/YYYY |
| Check digit | Last digit calculated from others | ISBN, barcode |
| Uniqueness check | Value has not been used already | Username or primary key |
Verification methods: double entry (type it twice and the computer compares, as with a new password) and a visual check (a person compares the screen with the original document).
mark = int(input("Mark (0-100): "))
while mark < 0 or mark > 100:
print("Invalid: enter a number from 0 to 100")
mark = int(input("Mark (0-100): "))
Test data
Test data is chosen to show the program works for every kind of input. Example: a program that accepts a whole-number mark from 0 to 100.
| Type | Meaning | Examples |
|---|---|---|
| Normal | Sensible data that should be accepted | 56 |
| Abnormal | Data that should be rejected | −5, 101, "abc", 45.5 |
| Extreme | The largest and smallest values that are accepted | 0 and 100 |
| Boundary | An extreme value together with the nearest value just outside it, which is rejected | 0 (accepted) and −1 (rejected); 100 (accepted) and 101 (rejected) |
12Trace tables
A trace table is a "dry run" on paper: one column for each variable (and output), one row for each change, so you can follow the algorithm step by step. It is used to find logic errors and to work out what an algorithm does. Fill in a value only in the row where it changes, unless the question says otherwise.
Total ← 0
Count ← 0
FOR i ← 1 TO 4
INPUT Num
IF Num MOD 2 = 0 THEN
Total ← Total + Num
Count ← Count + 1
ENDIF
NEXT i
OUTPUT Total, Count
Inputs in order: 5, 8, 3, 6. The algorithm totals and counts the even numbers.
| i | Num | Num MOD 2 = 0 | Total | Count | OUTPUT |
|---|---|---|---|---|---|
| 0 | 0 | ||||
| 1 | 5 | FALSE | |||
| 2 | 8 | TRUE | 8 | 1 | |
| 3 | 3 | FALSE | |||
| 4 | 6 | TRUE | 14 | 2 | |
| 14, 2 |
Programming
Python for the Paper 2 coding questions, with the matching Cambridge pseudocode: strings, arrays, files, subprograms, searching and sorting.
8.1Input, output and casting
input() always returns a string. Convert it (cast it) before doing arithmetic.
INPUT Name INPUT Age OUTPUT "Hello ", Name OUTPUT "Next year you will be ", Age + 1
name = input("Name: ")
age = int(input("Age: ")) # int() casts text
print("Hello", name)
print("Next year you will be", age + 1)
| Cast | Result |
|---|---|
| int("42") | 42 (whole number) |
| float("3.5") | 3.5 (decimal) |
| str(42) | "42" (text) |
Whole-number division and remainder: 17 // 5 is 3 and 17 % 5 is 2 (pseudocode DIV and MOD). Use round(x, 2) to round to 2 decimal places.
8.2Strings and upper / lower case
| Task | Pseudocode | Python |
|---|---|---|
| Length of text | LENGTH(Word) | len(word) |
| Convert to upper case | UCASE(Word) | word.upper() |
| Convert to lower case | LCASE(Word) | word.lower() |
| Part of a string | SUBSTRING(Word, 1, 3) | word[0:3] (position 0, 1, 2) |
| One character | Word[1] | word[0] |
| Character code | ASC("A") = 65 | ord("A") |
| Code to character | CHR(65) = "A" | chr(65) |
| Join strings | "Hi " & Name | "Hi " + name |
Strings cannot be changed in place; the methods above return a new string. Some versions of the pseudocode guide write TO_UPPER and TO_LOWER instead of UCASE and LCASE.
Why change case? To compare fairly. A user might type "YES", "yes" or "Yes"; converting the input first means one test covers them all.
answer = input("Play again? (yes/no): ").lower()
if answer == "yes":
print("Restarting")
word = input("Word: ").lower()
vowels = 0
for ch in word:
if ch == "a" or ch == "e" or ch == "i" or ch == "o" or ch == "u":
vowels = vowels + 1
print("Vowels:", vowels)
8.3One-dimensional arrays
Use a loop to fill and process an array. A loop with an index is the standard way to read, total or search every item.
DECLARE Marks : ARRAY[1:5] OF INTEGER FOR Index ← 1 TO 5 OUTPUT "Enter mark ", Index INPUT Marks[Index] NEXT Index
marks = [0, 0, 0, 0, 0] # 5 items, indexes 0 to 4
for i in range(5):
marks[i] = int(input("Enter mark " + str(i + 1) + ": "))
Useful list tools: len(marks) (number of items), marks.append(x) (add to the end), marks[-1] (last item).
names[2] and scores[2] both belong to the same person. Swap both arrays together when sorting.8.4Two-dimensional arrays
A 2D array is a table with rows and columns, and needs two indexes: Grid[row][column] in Python and Grid[row, column] in pseudocode. Use a nested loop: the outer loop moves down the rows and the inner loop moves across the columns.
DECLARE Grid : ARRAY[1:3, 1:3] OF INTEGER
FOR Row ← 1 TO 3
FOR Col ← 1 TO 3
Grid[Row, Col] ← 0
NEXT Col
NEXT Row
Grid[2, 3] ← 7
grid = [[0, 0, 0],
[0, 0, 0],
[0, 0, 0]]
grid[1][2] = 7 # row 2, column 3 (counting from 0)
total = 0
for r in range(3):
for c in range(3):
total = total + grid[r][c]
print("Total:", total) # 7
8.5File handling
Variables lose their values when a program ends. A text file keeps data between runs. The three modes are read, write (creates the file, or overwrites the old contents) and append (adds to the end). Always close the file when finished.
OPENFILE "scores.txt" FOR WRITE WRITEFILE "scores.txt", "Aung,85" WRITEFILE "scores.txt", "Su,91" CLOSEFILE "scores.txt"
file = open("scores.txt", "w")
file.write("Aung,85\n")
file.write("Su,91\n")
file.close()
DECLARE Line : STRING
OPENFILE "scores.txt" FOR READ
WHILE NOT EOF("scores.txt") DO
READFILE "scores.txt", Line
OUTPUT Line
ENDWHILE
CLOSEFILE "scores.txt"
file = open("scores.txt", "r")
for line in file: # loops until the end
print(line.strip()) # strip() removes \n
file.close()
file = open("scores.txt", "a")
file.write("Zin,67\n")
file.close()
names = []
scores = []
file = open("scores.txt", "r")
for line in file:
parts = line.strip().split(",") # "Aung,85" → ["Aung", "85"]
names.append(parts[0])
scores.append(int(parts[1]))
file.close()
\n so records run together; forgetting to close the file.8.6Procedures and functions
A procedure carries out a task. A function carries out a task and returns a value. Both can take parameters. Variables created inside are local (exist only in that subprogram); a global variable is available everywhere. Subprograms make code shorter, easier to test and reusable.
PROCEDURE Greet(Name : STRING)
OUTPUT "Hello ", Name
ENDPROCEDURE
FUNCTION Area(L : REAL, W : REAL) RETURNS REAL
RETURN L * W
ENDFUNCTION
CALL Greet("Aung")
Size ← Area(4, 2.5)
def greet(name):
print("Hello", name)
def area(l, w):
return l * w
greet("Aung")
size = area(4, 2.5)
8.7Linear search and bubble sort: complete programs
Chapter 7 explained the ideas. These are full versions with input, so you can run them.
names = ["Aung", "Su", "Zin", "Kyaw", "Mya"]
target = input("Name to find: ")
found = False
for i in range(len(names)):
if names[i].lower() == target.lower():
print("Found at position", i + 1)
found = True
if not found:
print("Not found")
marks = [72, 85, 60, 91, 55]
n = len(marks)
for i in range(n - 1):
swapped = False
for j in range(n - 1 - i):
if marks[j] > marks[j + 1]:
temp = marks[j]
marks[j] = marks[j + 1]
marks[j + 1] = temp
swapped = True
if not swapped:
break
print(marks) # [55, 60, 72, 85, 91]
To sort into descending order, change > to < in the comparison.
Databases
Storing data in a table, choosing a primary key, and writing SQL to find what you need.
9.1Database concepts
A database is an organised collection of data. In a table, each field is a column (one piece of data about every item), each record is a row (everything about one item), and the table holds many records. The syllabus uses single-table databases only.
- Primary key
- A field whose value is unique for every record, so it identifies exactly one record. It cannot be empty or duplicated. Examples: StudentID, ISBN.
- Data types
- Text (alphanumeric), Character, Integer, Real, Boolean (Yes/No) and Date/Time. Choose the one that matches the data; a phone number is text.
- Validation
- Range, length, type, presence and format checks stop bad data entering a field.
The sample table used below is called Students. StudentID is the primary key.
| StudentID | FirstName | LastName | Class | Grade |
|---|---|---|---|---|
| S001 | Aung | Kyaw | 10A | 82 |
| S002 | Su | Mon | 10A | 91 |
| S003 | Zin | Htet | 10B | 67 |
| S004 | Kaung | Min | 10B | 78 |
| S005 | Hla | Hla | 10A | 55 |
| S006 | Thura | Oo | 10B | 88 |
9.2Structured Query Language (SQL)
SELECT field1, field2 -- which columns to show (* means all fields) FROM table -- which table WHERE condition -- which records (optional) ORDER BY field ASC|DESC; -- sort order (optional; ASC is the default)
| Item | Notes |
|---|---|
| = <> < <= > >= | Comparison operators. Text values go in quotes: Class = "10A". |
| AND OR | Combine conditions. |
| LIKE | Pattern match with a wildcard: FirstName LIKE "S%" finds names starting with S. |
| SUM(field) | Adds up the values in a numeric field. |
| COUNT(field) | Counts the records. |
Worked queries on the Students table
SELECT FirstName, LastName FROM Students WHERE Grade >= 80 ORDER BY LastName ASC;
| FirstName | LastName |
|---|---|
| Aung | Kyaw |
| Su | Mon |
| Thura | Oo |
SELECT StudentID, FirstName, Grade FROM Students WHERE Class = "10A" AND Grade > 60;
| StudentID | FirstName | Grade |
|---|---|---|
| S001 | Aung | 82 |
| S002 | Su | 91 |
SELECT * FROM Students ORDER BY Grade DESC;
Shows all fields, with the highest grade first: S002 (91), S006 (88), S001 (82), S004 (78), S003 (67), S005 (55).
SELECT COUNT(StudentID) FROM Students WHERE Class = "10A"; -- result: 3 SELECT SUM(Grade) FROM Students WHERE Class = "10B"; -- result: 233 (67 + 78 + 88)
- Forgetting the semicolon at the end or the quotes around text.
- Writing fields in
SELECTthat the question did not ask for. - Using
=when the question needs>=("at least" means greater than or equal to).
Boolean Logic
Logic gates, truth tables, and turning a written condition into a circuit.
10.1Logic gates
A logic gate takes one or more binary inputs (1 = true / on, 0 = false / off) and gives one output. NOT has one input; every other gate you need has two. Try each one:
Try it: gate playground
Switch A and B on and off. Each gate shows its output. NOT uses only A.
| Gate | Rule | Boolean form |
|---|---|---|
| NOT | Output is the opposite of the input | X = NOT A |
| AND | Output 1 only when both inputs are 1 | X = A AND B |
| OR | Output 1 when at least one input is 1 | X = A OR B |
| NAND | NOT AND: the opposite of AND | X = NOT (A AND B) |
| NOR | NOT OR: the opposite of OR | X = NOT (A OR B) |
| XOR | Output 1 when the inputs are different | X = A XOR B |
Truth tables
| A | B | AND | OR | NAND | NOR | XOR |
|---|---|---|---|---|---|---|
| 0 | 0 | 0 | 0 | 1 | 1 | 0 |
| 0 | 1 | 0 | 1 | 1 | 0 | 1 |
| 1 | 0 | 0 | 1 | 1 | 0 | 1 |
| 1 | 1 | 1 | 1 | 0 | 0 | 0 |
| A | NOT A |
|---|---|
| 0 | 1 |
| 1 | 0 |
10.2Logic circuits and truth tables
Circuits join gates so that the output of one is the input of another. Work from the inputs towards the output, and add one column for every gate. With n inputs a truth table has 2n rows (two inputs: 4 rows; three inputs: 8 rows). List the input rows in binary counting order.
From a statement to an expression
"An alarm (X) sounds if the door is open (A) and the system is armed (B), or the panic button (C) is pressed." Becomes X = (A AND B) OR C. Words map straight to gates: and → AND, or → OR, not → NOT.
Try it: truth table builder
Choose an expression. The table shows the working column for each gate.
Mind maps · Chapters 1 to 10
One-page visual summaries for quick revision. Each map opens in a new tab on Google Drive.