Skip to content
Visual revision

Infographics

Every syllabus topic, drawn the way examiners expect you to draw it — grouped by course and topic, 63 unique diagrams. Download as PNG for your notes, print them, stick them on the wall.

88 diagrams · 63 unique

O Level

2210

Paper 1 · 1. Data Representation open topic →

Number system conversionsDenary ↔ binary ↔ hexadecimal — the routes the exam expects.Denarybase 10 · 0–9Binarybase 2 · 0,1Hexbase 16 · 0–9, A–F÷2, read remainders upadd place values 128…1group 4 bits → digiteach digit → 4 bitsdenary ↔ hex: go via binary (or ÷16 / ×16)128643216842110110110= 128+32+16+4+2= 182 = B6₁₆Two's complement: invert all bits, add 1. Left shift ×2, right shift ÷2.Hex is used for MAC addresses, colour codes, memory dumps and error codes.cswithzak.com

Number system conversions

O Level 1. Data Representation · AS Level 1. Information Representation

O LevelAS
File size calculationsWork in bits first, then ÷ 8 for bytes, then ÷ 1024 for each step up. Show every line of working.IMAGE (bitmap)size = width × height × colour depth1024 × 768 × 24 bits= 18 874 368 bits ÷ 8= 2 359 296 bytes ÷ 1024= 2304 KiB = 2.25 MiBcolour depth 24 bits = 16.7 million colours (2²⁴)SOUNDsize = sample rate × resolution × seconds44 100 Hz × 16 bits × 30 s= 21 168 000 bits ÷ 8= 2 646 000 bytes ÷ 1024≈ 2584 KiB ≈ 2.52 MiB (×2 if stereo)higher sample rate / resolution = better quality, bigger filebitnibble×4byte×2KiB×1024MiB×1024GiB×1024TiB×1024PiB×1024EiB×10241 nibble = 4 bits · 1 byte = 8 bits · 1 KiB (kibibyte) = 1024 bytes · 1 MiB = 1024 KiB · 1 GiB = 1024 MiB · 1 TiB = 1024 GiBBinary prefixes (kibi, mebi, gibi…) are powers of 2. Decimal prefixes (kilo, mega, giga…) are powers of 10: 1 kB = 1000 bytes.Resolution = number of pixels (w × h). Colour depth = bits per pixel.Sample rate = samples per second (Hz). Sample resolution = bits per sample.Compression: lossy (MP3, JPEG) discards data permanently; lossless (RLE, PNG, ZIP) restores the original exactly.cswithzak.com

File size calculations

O Level 1. Data Representation · AS Level 1. Information Representation

O LevelAS
Two's complement, overflow & shifts8-bit two's complement: the MSB is worth −128. Range −128 … +127. Same bits, different meaning — saywhich you are using.Negating +37 → −37+370010010132 + 4 + 1invert11011010flip every bit (one’s complement)+111011011= −128 + 64 + 16 + 8 + 2 + 1 = −37 ✓Shortcut: from the right, copy up to and including the first 1, then flip the rest.Overflow0111111112700000001+ 110000000= −128 ✗ does not fit in 8 bitsOverflow = the answer needs more bits than the register has.Sign flips: two positives give a negative (or vice-versa).ShiftsShift0001 0110 (22) →logical left 10010 1100 (44)logical right 10000 1011 (11)arithmetic right 1keeps the sign bit1111 0100 (−12) →1111 1010 (−6)Left ×2, right ÷2. Bits shifted out are lost — that isanother cause of overflow. Logical fills with 0s.BCD: each denary digit as its own 4-bit nibble — 47 = 0100 0111. Used where exact decimals matter (currency).cswithzak.com

Two's complement, overflow & shifts

O Level 1. Data Representation · AS Level 1. Information Representation · AS Level 4. Processor Fundamentals

O LevelAS
Bitmap vs vector graphics & digital soundBitmap = grid of pixels. Vector = list of drawing commands. Sound = analogue wave measured (sampled) atregular intervals.BITMAP8 × 6 pixels · 1 bit eachVECTORellipse(56,42,44,30) line(…)BitmapVectorStored ascolour of every pixelobjects + propertiesResizepixelates / blursscales perfectlyFile sizeresolution × colour depthdepends on object countBest forphotos, scanslogos, fonts, CAD, mapsFormatsBMP, JPEG, PNG, GIFSVG, EPS, AIImage resolution = pixels per inch / total pixels. Colour depth = bits per pixel: 1 bit → 2 colours, 8 bits → 256, 24 bits → 16.7 M.File header stores width, height, colour depth. 2210/9618 both want: file size = W × H × depth (+ header).Sampling sound111100000Sampling rate = samples per second (Hz). CD quality = 44.1 kHz.Sampling resolution = bits per sample (8 levels shown = 3 bits).Higher rate → closer to the analogue wave; higher resolution →finer amplitude steps. Both increase the file size.size = rate × resolution × seconds (× 2 for stereo).Vector = drawing list, bitmap = colour of every pixel — so a vector logo scales cleanly and a bitmap photo does not.cswithzak.com

Bitmap, vector & sound

AS Level 1. Information Representation · O Level 1. Data Representation

ASO Level
Lossless vs lossy compressionWhy compress? Less storage, faster transmission, less bandwidth. The question is whether you can get theoriginal back.LOSSLESSoriginal restored exactly — RLE, ZIP, PNG, FLAC, GIFLOSSYdetail discarded for ever — JPEG, MP3, MP4, AACRun-length encoding (RLE)AAAABBBCCDAA4A3B2C1D2A12 → 10 bytes. RLE wins only with long runs (flat colour areas).Also: LZ (repeated patterns), Huffman (short codes, common symbols).What lossy actually removesImages (JPEG): merge near-identical colours, reduce colour depthor resolution — the eye cannot tell the difference.Sound (MP3): remove frequencies humans cannot hear, quietersounds masked by louder ones; lower sample rate / resolution.Video (MPEG): store only the changes between frames.Result: much smaller files, but quality is permanently lower.LosslessLossyData lost?none — bit-for-bit identical after decompressionyes — cannot recover the originalCompression ratiolower (depends on the data)much higher (adjustable quality)Use whentext, programs, spreadsheets, medical imagesphotos, music, streaming videoExam tip: if the question says “the file must be restored exactly” → lossless; “smallest possible for the web” → lossy.cswithzak.com

Lossless vs lossy compression

AS Level 1. Information Representation · O Level 1. Data Representation

ASO Level

Paper 1 · 2. Data Transmission open topic →

Data packets & transmission modesA packet = header + payload + trailer. Packets can take different routes and are re-ordered at thedestination.HEADERsender IP · destination IP · packet №PAYLOADthe actual data (typically 64 KiB max)TRAILERend marker · error check (CRC)Serial vs parallel10110010serial: 1 wire, bits one after another — cheap, long distance, no skewparallel: 8 wires, whole byte at once — fast but short distance, skewSimplex · half-duplex · full-duplexsimplex — one direction only (sensor → computer, keyboard → computer)half-duplex — both directions, one at a time (walkie-talkie)full-duplex — both directions at the same time (phone call, broadband)USB is serial: auto-detects the device and installs its driver, backward compatible, but cable length is limited (≈ 5 m).cswithzak.com

Data packets & transmission modes

O Level 2. Data Transmission

O Level
Error detection methodsData can be corrupted by interference during transmission. Each method answers: how is the error found?Parity checkEven parity: number of 1s must be even.1011 0010 → four 1s ✓ (parity bit = bit 8)Fails if two bits flip. A parity block(rows + columns) can locate the bad bit.ChecksumSender adds all bytes, sends the total.Receiver recalculates and compares.Mismatch → request the block again.Cheap; catches most bursts of errors.Echo checkReceiver sends the data straight back.Sender compares it with the original.Weakness: which copy got corrupted?Used with retransmission.Check digitAn extra digit calculated from the other digits (ISBN-13,barcodes: modulo-10 weighting). Recalculated on entry —catches a wrong, missing or transposed digit.ARQ — Automatic Repeat reQuestReceiver checks the data (parity / checksum). Correct →sends ACK. Error, or no ACK before the time-out →the sender automatically retransmits the block.Symmetric encryption: one shared key encrypts and decrypts. Asymmetric: public key encrypts, matching private key decrypts.Encryption protects meaning if data is intercepted — it does not detect errors. Parity, checksum and echo check do.cswithzak.com

Error detection methods

O Level 2. Data Transmission · AS Level 6. Security, Privacy and Data Integrity

O LevelAS
Circuit switching vs packet switchingBoth get data from A to B across a network of routers. The difference is whether a path is reservedfirst.Circuit switchingAR1R2R3R4B1. A dedicated end-to-end path is set up before any data is sent.2. Every bit follows the same route, in order, at a guaranteed rate.3. The path is held (and paid for) until the call ends — even if idle.Used for: traditional telephone calls.Packet switchingAR1R2R3R4B1. Data is split into packets, each with a header (addresses, no.).2. Routers forward each packet independently — routes can differ.3. Packets may arrive out of order; re-ordered by packet number.Used for: the internet (IP), email, web, streaming.Circuit switchingPacket switchingSet-uppath reserved first (delay before start)none — send immediatelyReliability / orderguaranteed, in orderpackets can be lost or arrive out of orderEfficiencywastes capacity when idlelinks shared; copes with node failurecswithzak.com

Circuit vs packet switching

A2 Level 14. Communication and Internet Technologies · O Level 2. Data Transmission

A2O Level

Paper 1 · 3. Hardware open topic →

Von Neumann architectureOne memory holds both instructions and data; CPU and memory talk over three buses.CPUControl Unitdecodes, sends signalsALUarithmetic & logicRegistersPC · MAR · MDR · CIR · ACCCachefast memory for frequently used dataMain memoryRAM — instructions + dataaddress bus →data bus ⇄control bus ⇄Address bus is unidirectional (CPU → memory). Its width sets the maximum addressable memory (n lines → 2ⁿ addresses).cswithzak.com

Von Neumann architecture

O Level 3. Hardware · AS Level 4. Processor Fundamentals

O LevelAS
Fetch – Decode – Execute cycleRegister transfer notation for the fetch stage — learn it word for word.FETCHinstruction from memoryDECODEcontrol unit interprets opcodeEXECUTEALU / registers / memoryrepeat (check for interrupts at the end of each cycle)1. MAR ← [PC]2. PC ← [PC] + 13. MDR ← [[MAR]]4. CIR ← [MDR]address of next instruction → MARincrement ready for the next fetchcontents of that address → MDRcopy the instruction into CIRcswithzak.com

Fetch–Decode–Execute cycle

O Level 3. Hardware · AS Level 4. Processor Fundamentals

O LevelAS
Primary, secondary & virtual storagePrimary = accessed directly by the CPU. Secondary = permanent, not directly accessed. Off-line =removable. Cloud = remote.PRIMARYRAM — volatile, read/write; holds therunning programs and data; more RAM= fewer swaps to virtual memory.ROM — non-volatile, read-only; holds thefirmware / bootstrap loader (BIOS)that starts the computer.SECONDARYMagnetic (HDD): spinning platters,r/w heads; cheap per GB; moving parts.Optical (CD/DVD/Blu-ray): laser readspits & lands on a spiral track.Solid state (SSD, flash): NAND transistors,no moving parts — fast, quiet, robust.OFF-LINE / CLOUDRemovable: USB flash, external HDD,optical discs — backups and transfer.Cloud: files stored on remote servers,accessed over the internet.+ anywhere access, automatic backup– needs connection, privacy, cost.Virtual memoryRAMpages of running programsHDD / SSDswap / page filepage out (not needed now)page in (needed again)Lets programs biggerthan RAM run; moreprograms at once.Slower than RAM;disk thrashing whenpages swap constantly.Why secondary storage? RAM is volatile — unsaved work is lost at power-off. Why RAM? It is far faster than any secondary storage.Sizes: bit → nibble → byte → KiB → MiB → GiB → TiB (×1024). Embedded systems keep their program in ROM/flash.cswithzak.com

Primary, secondary & virtual storage

O Level 3. Hardware

O Level

Paper 1 · 4. Software open topic →

How an interrupt is handledA signal that tells the processor an event needs attention now — without it, the CPU would have to keeppolling every device.SourcesHardwarekey press / mouse clickprinter out of papertimer (time-slice ended)hardware fault, power failureSoftwaredivision by zeroarithmetic overflowillegal / undefined instructiontwo processes need one resource1Device or program raises an interrupt → interrupt flag is set2CPU finishes the current fetch–decode–execute cycle, then tests the flag3Higher priority? Push the registers (PC, ACC, …) onto the stack4Load the ISR (interrupt service routine) address into the PC; run it5Pop the saved registers off the stack; resume the interrupted programPriorities: a low-priority interrupt can itself be interrupted by a higher one (nested); lower ones wait in a queue.The interrupt flag is tested once per cycle — that is why “check for interrupts” is the last step of the FDE cycle.Buffers + interrupts let a slow printer work while the CPU carries on: it interrupts only when its buffer needs refilling.cswithzak.com

How an interrupt is handled

O Level 4. Software · AS Level 4. Processor Fundamentals

O LevelAS
Compiler · Interpreter · AssemblerAll three are translators: they turn what you wrote into machine code the processor can execute.High-level sourceCompilerExecutable file (then run)High-level sourceInterpreterruns each line (as it goes)Assembly (LDA, ADD…)AssemblerMachine code (one-to-one)CompilerInterpreterTranslateswhole program before it runsone statement at a time, while runningErrorsall listed at the end; nothing runsstops at the first error it meetsSpeedfast — already machine codeslower — translated every runSource needed?no: executable can be distributedyes: source + interpreter every timeBest forfinished software, games, appsdeveloping and debuggingHigh-level: portable, English-like, easy to write and debug. Low-level: direct hardware control, fast, machine-specific.IDE: editor, translator, run-time, debugger (breakpoints, single-step, variable watch), auto-complete, pretty-print.cswithzak.com

Compiler, interpreter & assembler

O Level 4. Software · AS Level 5. System Software

O LevelAS
What the operating system doesThe OS is the layer between the hardware and everything else: it hides complexity and shares resourcesbetween programs.HardwareOperating systemUtility & library softwareApplication softwareUserrequests go down the layers; results come back upOS functionsmemory management (allocate, protect, virtual)process management & multitasking (scheduling)file management (names, folders, access rights)hardware / peripheral management (device drivers)security: user accounts, passwords, access levelsuser interface: GUI (icons, windows) or CLIinterrupt handling; error reportingplatform for running application softwareUtility softwaredisk formatter · defragmenter · backupvirus checker · file compressiondisk contents analysis / repairProgram libraries & DLLsLibrary = pre-written, tested routines you can call.DLL (dynamic link library): loaded only at run timeand shared by many programs → smaller executables,fixes reach every program at once; but a missing orchanged DLL breaks the program.O Level: firmware & bootstrapFirmware in ROM runs first, loads the bootstrap, which loads the OSfrom secondary storage into RAM. Then the OS takes over.Exam wording: “the OS manages …” — name the resource (memory, files, devices, processes, users) and what that involves.cswithzak.com

What the operating system does

O Level 4. Software · AS Level 5. System Software

O LevelAS

Paper 1 · 5. The Internet and Its Uses open topic →

URL anatomy & how a web page reaches youInternet = the physical network of networks. World Wide Web = the pages and services that run on it,fetched with HTTP(S).https://protocolwww.cswithzak.comdomain name (host)/learn/o-levelpath / file nameHTTPS = HTTP + SSL/TLS encryption(padlock: data encrypted in transit)Browseron your deviceDNS serverdomain name → IPWeb serverhosts the page1 “IP for this name?”2 “104.21.5.6”3 HTTP(S) GET request sent to that IP address4 HTML sent back → browser interprets it and renders the pageCookiesSession cookie: held in memory, deleted when the browser closes. Persistent cookie: saved to disk until it expires.Uses: keep you logged in, remember preferences/language, shopping basket, track browsing for adverts.Browser: renders HTML, runs JavaScript, keeps history, bookmarks and tabs, stores cookies.Blockchain: a chain of time-stamped blocks, each holding a hash of the previous block — tampering breaks the chain.A DNS server with no record asks a higher-level DNS server. Packets are routed to the IP address, never the name.cswithzak.com

URL anatomy & fetching a web page

O Level 5. The Internet and Its Uses

O Level
Cyber security: threats vs defencesAim → describe the threat, its effect on the data or user, and the matching prevention. Always pair themup.ThreatWhat happensPrevent it withBrute-forcetrying every possible password until one workslong complex passwords, lock-out, 2FADDoSa botnet floods a server with requests until it failsfirewall, proxy server, traffic filteringHackingunauthorised access to a system to steal or change datafirewall, strong passwords, 2FA, encryptionMalwarevirus, worm, Trojan, spyware, adware, ransomwareanti-malware, updates, backupsPhishingfake email/text lures you to a fake site to enter detailscheck sender & URL, spam filter, awarenessPharmingmalicious code redirects a real URL to a fake websitecheck SSL certificate/padlock, anti-malwareSocial engineeringmanipulating people rather than systems (calls, pretexts)staff training, verify requests, policiesDefence toolkitaccess levelsanti-malwareauthenticationbiometricstwo-factor (2FA)firewallprivacy settingsproxy serverSSL / HTTPSauto-updatesbackupsEncryption makes intercepted data unreadable without the key. Firewall: filters traffic by rules. Proxy: also hides the real server.Virus: needs a host file · Worm: self-replicates across the network · Trojan: hides in legitimate-looking softwareSpyware: records keystrokes · Adware: unwanted adverts · Ransomware: encrypts your files until you paycswithzak.com

Cyber threats vs defences

O Level 5. The Internet and Its Uses · AS Level 6. Security, Privacy and Data Integrity

O LevelAS

Paper 1 · 6. Automated and Emerging Technologies open topic →

Automated system: sensor → microprocessor → actuatorA feedback loop: the actuator changes the environment, the sensor measures it again, and the cyclerepeats.Sensormeasures the environmentADCanalogue → digitalMicroprocessorcompares with stored valueActuatormotor, valve, heaterfeedback: the environment changes, the sensor reads the new valueSensors you can nametemperature · light · pressure · moisture · humidity · pH · infra-red · motion · acoustic · gasflow · level · proximity · magnetic field · accelerometerWorked example — greenhouseIF Temp > 25 THEN open vent (actuator ON)IF Temp < 18 THEN heater ONELSE no action — loop back and read the sensor againWhy automate?+ faster, consistent, 24/7, safer in hazardous places+ no human error; can be more efficient with resources– expensive to set up and maintain; single point of failure– depends on sensor accuracy; can be hackedRobot = mechanical structure + electrical parts (sensors, microprocessor) + programmable. Most just repeat instructions.cswithzak.com

Automated systems: sensor → actuator

O Level 6. Automated and Emerging Technologies

O Level
Artificial intelligence: expert systems & machine learningAI collects data and rules, uses them to reason, and can learn from mistakes. Two flavours are on thesyllabus.Expert systemUser interfacequestions in, advice outInference engineapplies rules to factsKnowledge basefacts from expertsRule baseIF … THEN … rulesExplanation system: says WHY it reached a conclusion.Examples: medical diagnosis, fault finding, chess, oil prospecting, tax.+ consistent, always available, keeps rare expertise– needs experts to build it and keep it up to dateMachine learningDataexamplesTrainingfind patternsModelPrediction on new datathe program adapts without being reprogrammedLearns from experience: spam filters, recommendation, speechrecognition, self-driving cars, fraud detection.Accuracy improves as more data is processed.Characteristics of AI (syllabus wording)collection of data and rulesability to reasonability to learn and adaptExpert system = knowledge base + rule base + inference engine + user interface. Learn what each part does.Machine learning is a subset of AI: the system improves its performance from data rather than fixed rules only.cswithzak.com

Expert systems & machine learning

O Level 6. Automated and Emerging Technologies

O Level

Paper 2 · 7. Algorithm Design and Problem-Solving open topic →

Flowchart symbolsUse exactly these shapes. Every decision has two labelled exits; flow lines carry arrows; one START, oneSTOP.TerminatorSTART / STOPProcessTotal ← Total + NInput / OutputINPUT N · OUTPUT TotalDecisionN > 0 ? → Yes / NoSubroutinepredefined process / callflow line (arrow)STARTINPUT NumNum > 0 ?YesOUTPUT "Positive"NoOUTPUT "Not +"STOPProgram development life cycleAnalysisDesignCodingTestingAnalysis (abstraction, decomposition → requirements) · Design (structure diagram, flowchart, pseudocode) · Coding · Testingcswithzak.com

Flowchart symbols & the PDLC

O Level 7. Algorithm Design and Problem-Solving · AS Level 9. Algorithm Design and Problem-Solving

O LevelAS
Bubble sort — one pass, step by stepCompare each pair of neighbours; swap if out of order. After pass 1 the biggest is last; after pass n−1everything is sorted.5381compare 5 and 3 → 5 > 3, swap3581compare 5 and 8 → in order, no swap3581compare 8 and 1 → 8 > 1, swap3518end of pass 1: the largest value is now lastPass 2 → 3 1 5 8 · Pass 3 → 1 3 5 8. Each pass needs one fewer comparison. Stop early if a pass makes no swaps.FOR i ← 1 TO N - 1 FOR j ← 1 TO N - i IF A[j] > A[j+1] THEN Temp ← A[j] A[j] ← A[j+1] A[j+1] ← Temp ENDIF NEXT jNEXT iFlag version: REPEAT … Swapped ← FALSE… set TRUE on any swap … UNTIL NOT SwappedLinear search (the other standard algorithm)Found ← FALSE : i ← 1 : WHILE i ≤ N AND NOT Found → IF A[i] = Target THEN Found ← TRUE ELSE i ← i + 1Works on unsorted data; checks every item in the worst case. Binary search (AS) needs sorted data and halves the list each time.Totalling: Total ← Total + Value · Counting: Count ← Count + 1 when true · Max/min: compare with the current bestcswithzak.com

Bubble sort & linear search

O Level 7. Algorithm Design and Problem-Solving · AS Level 10. Data Types and Structures

O LevelAS
Choosing test dataRule under test: “enter a mark from 0 to 100”. Each type of test data has a job — name the type AND saywhy it is chosen.-1050100101accepted range 0 … 100rejectedrejectedTypePurposeExamples hereNormaltypical valid data the program should accept and process23, 50, 87Extremevalid data at the very limits of the accepted range0 and 100Boundaryeither side of each limit: last accepted, first rejected-1 / 0 and 100 / 101Abnormalinvalid (erroneous) data the program must reject-5, 150, “abc”, 3.7Validation: is the data sensible? range · type · length · format · presence · check digit checks.Verification: was it entered correctly? double entry, visual check.Trace table / dry run: one column per variable and the output, one row per change — the way to find logic errors.9618 adds: walkthrough (people read the code), alpha (in-house), beta (real users before release), acceptance (the client signs off).cswithzak.com

Choosing test data

O Level 7. Algorithm Design and Problem-Solving · AS Level 12. Software Development

O LevelAS

Paper 2 · 8. Programming open topic →

Three kinds of loopCount-controlled: you know how many times. Pre-condition: may run 0 times. Post-condition: must run atleast once.Count-controlledFOR … NEXTFOR i ← 1 TO 5 OUTPUT iNEXT iFOR i ← 10 TO 0 STEP -2• known number of repetitions• loop variable set automatically• STEP changes the incrementPre-conditionWHILE … ENDWHILETotal ← 0INPUT NWHILE N <> -1 Total ← Total + N INPUT NENDWHILE• condition tested BEFORE each pass• may run 0 times• sentinel value ends the loopPost-conditionREPEAT … UNTILREPEAT INPUT MarkUNTIL Mark >= 0 AND Mark <= 100// validation loop• condition tested AFTER each pass• always runs at least once• perfect for input validationSelection remindersIF x > 0 THEN … ELSE … ENDIF · CASE OF Choice 1 : … 2 : … OTHERWISE … ENDCASEClose every construct: NEXT · ENDWHILE · UNTIL · ENDIF · ENDCASE. One ENDIF per IF. Indent the body. ← assigns, = compares.Nested loops: the inner loop runs fully for each outer pass (2D array: FOR Row … FOR Col … NEXT Col … NEXT Row).cswithzak.com

Three kinds of loop

O Level 8. Programming · AS Level 11. Programming

O LevelAS
Procedure vs functionBoth are named subroutines with parameters. The difference: a function RETURNS a value, so you use itinside an expression.PROCEDUREPROCEDURE Greet(Name : STRING) OUTPUT "Hello ", NameENDPROCEDURECALL Greet("Ali") // stands alone• does a task (output, update an array…)• called with CALL as a statement• no RETURN value (may change BYREF parameters)FUNCTIONFUNCTION Square(N : INTEGER) RETURNS INTEGER RETURN N * NENDFUNCTIONArea ← Square(5) + 1 // used in an expression• calculates and RETURNS exactly one value• called inside an expression / assignment / OUTPUT• must declare the RETURNS type in the headerParameters & scopeParameter = value passed in via the brackets (Name, N above). Argument = the actual value used in the call (“Ali”, 5).Local: declared inside the subroutine, exists only while it runs. Global: declared at the top, visible everywhere.Why use subroutines? Reuse, easier testing, shorter main program, several people can work on it, easier maintenance.Library routines you must know: MOD, DIV, ROUND, RANDOM (2210) · LENGTH, SUBSTRING/MID, UCASE, LCASE, INT, RAND (9618).cswithzak.com

Procedure vs function

O Level 8. Programming · AS Level 11. Programming

O LevelAS
Arrays, records & text filesAn array holds many values of ONE type under one name. A record groups DIFFERENT types. A text filekeeps data permanently.1D array — DECLARE Marks : ARRAY[1:5] OF INTEGER[1]72[2]58[3]91[4]64[5]80Marks[3] ← 91 · FOR i ← 1 TO 5 … NEXT i2D array — DECLARE Grid : ARRAY[1:3, 1:4] OF CHAR......X.....row 1row 2row 3col 1col 2col 3col 4Grid[2, 3] ← 'X' // [row, column]Walk it with nested loops: FOR Row … FOR Col … NEXT Col … NEXT RowRecord (composite type)TYPE StudentRec DECLARE Name : STRING DECLARE Mark : INTEGER DECLARE Passed : BOOLEANENDTYPEDECLARE S : StudentRecS.Mark ← 72Text fileOPENFILE "marks.txt" FOR READ // or WRITE / APPENDWHILE NOT EOF("marks.txt") READFILE "marks.txt", Line OUTPUT LineENDWHILECLOSEFILE "marks.txt"WRITEFILE "marks.txt", "Ali,72" // needs FOR WRITEcswithzak.com

Arrays, records & text files

AS Level 10. Data Types and Structures · O Level 8. Programming

ASO Level

Paper 2 · 9. Databases open topic →

Single-table database & SQLField = column (one item of data). Record = row (one entity). Primary key = the field that uniquelyidentifies each record.STUDENTStudentIDNameFormMarkS001Ali10A82S002Hina10B64S003Omar10A91S004Sara10B70StudentID = primary key (unique, never blank).Data types: text, character, Boolean, integer, real, date/time.SELECT Name, MarkFROM STUDENTWHERE Mark >= 70ORDER BY Mark DESC;NameMarkOmar91Ali82Sara70result: 3 records,2 fields, sortedhighest firstAggregatesSELECT COUNT(*) FROM STUDENT WHERE Form = "10A"; → 2SELECT SUM(Mark) FROM STUDENT; → 307ClauseMeaningSELECTwhich fields to show (* = all)FROMwhich tableWHEREcondition: = < > <= >= <> AND ORORDER BYsort: ASC (default) or DESCValidation on fields: range, type, length,format, presence, check digit.Strings in quotes; the semicolon ends the statement.Field names in SELECT are separated by commas.cswithzak.com

Single-table database & SQL

O Level 9. Databases · AS Level 8. Databases

O LevelAS

Paper 2 · 10. Boolean Logic open topic →

Logic gate symbols & rulesDraw these exactly. A small circle on the output means NOT (inversion).ABXAND1 only if both 1X = A.BABXOR1 if either is 1X = A+BAXNOTinverts the inputX = ĀABXNAND0 only if both 1X = (A.B)‾ABXNOR1 only if both 0X = (A+B)‾ABXXOR1 if inputs differX = A⊕Bcswithzak.com

Logic gate symbols

O Level 10. Boolean Logic · AS Level 3. Hardware

O LevelAS
From logic circuit to truth tableX = (A AND B) OR (NOT C). Work out the intermediate columns first — that is where the marks are.ABCANDNOTORXA AND BNOT CABCA AND BNOT CX000011001000010011011000100011101000110111111101Method1. Inputs: n inputs → 2ⁿ rows, count in binary 000 → 111.2. One column per gate output, left to right through the circuit.3. Final column X is the last gate’s output.4. Expression from circuit: work from inputs to output, bracketing each gate.Writing the expressionX = (A AND B) OR (NOT C)9618 Boolean algebra: X = A.B + C̄NAND/NOR/XOR circuits build the same way.Draw the correct gate shapes, inputs on the left, output on the right; lines that join must have a junction dot.Check: a circuit with 3 inputs must have 8 rows; a truth-table answer with fewer rows loses the mark.cswithzak.com

From logic circuit to truth table

O Level 10. Boolean Logic · AS Level 3. Hardware · A2 Level 15. Hardware and Virtual Machines

O LevelASA2

AS Level

9618

Paper 1 · 1. Information Representation open topic →

Number system conversionsDenary ↔ binary ↔ hexadecimal — the routes the exam expects.Denarybase 10 · 0–9Binarybase 2 · 0,1Hexbase 16 · 0–9, A–F÷2, read remainders upadd place values 128…1group 4 bits → digiteach digit → 4 bitsdenary ↔ hex: go via binary (or ÷16 / ×16)128643216842110110110= 128+32+16+4+2= 182 = B6₁₆Two's complement: invert all bits, add 1. Left shift ×2, right shift ÷2.Hex is used for MAC addresses, colour codes, memory dumps and error codes.cswithzak.com

Number system conversions

O Level 1. Data Representation · AS Level 1. Information Representation

O LevelAS
File size calculationsWork in bits first, then ÷ 8 for bytes, then ÷ 1024 for each step up. Show every line of working.IMAGE (bitmap)size = width × height × colour depth1024 × 768 × 24 bits= 18 874 368 bits ÷ 8= 2 359 296 bytes ÷ 1024= 2304 KiB = 2.25 MiBcolour depth 24 bits = 16.7 million colours (2²⁴)SOUNDsize = sample rate × resolution × seconds44 100 Hz × 16 bits × 30 s= 21 168 000 bits ÷ 8= 2 646 000 bytes ÷ 1024≈ 2584 KiB ≈ 2.52 MiB (×2 if stereo)higher sample rate / resolution = better quality, bigger filebitnibble×4byte×2KiB×1024MiB×1024GiB×1024TiB×1024PiB×1024EiB×10241 nibble = 4 bits · 1 byte = 8 bits · 1 KiB (kibibyte) = 1024 bytes · 1 MiB = 1024 KiB · 1 GiB = 1024 MiB · 1 TiB = 1024 GiBBinary prefixes (kibi, mebi, gibi…) are powers of 2. Decimal prefixes (kilo, mega, giga…) are powers of 10: 1 kB = 1000 bytes.Resolution = number of pixels (w × h). Colour depth = bits per pixel.Sample rate = samples per second (Hz). Sample resolution = bits per sample.Compression: lossy (MP3, JPEG) discards data permanently; lossless (RLE, PNG, ZIP) restores the original exactly.cswithzak.com

File size calculations

O Level 1. Data Representation · AS Level 1. Information Representation

O LevelAS
Two's complement, overflow & shifts8-bit two's complement: the MSB is worth −128. Range −128 … +127. Same bits, different meaning — saywhich you are using.Negating +37 → −37+370010010132 + 4 + 1invert11011010flip every bit (one’s complement)+111011011= −128 + 64 + 16 + 8 + 2 + 1 = −37 ✓Shortcut: from the right, copy up to and including the first 1, then flip the rest.Overflow0111111112700000001+ 110000000= −128 ✗ does not fit in 8 bitsOverflow = the answer needs more bits than the register has.Sign flips: two positives give a negative (or vice-versa).ShiftsShift0001 0110 (22) →logical left 10010 1100 (44)logical right 10000 1011 (11)arithmetic right 1keeps the sign bit1111 0100 (−12) →1111 1010 (−6)Left ×2, right ÷2. Bits shifted out are lost — that isanother cause of overflow. Logical fills with 0s.BCD: each denary digit as its own 4-bit nibble — 47 = 0100 0111. Used where exact decimals matter (currency).cswithzak.com

Two's complement, overflow & shifts

O Level 1. Data Representation · AS Level 1. Information Representation · AS Level 4. Processor Fundamentals

O LevelAS
Bitmap vs vector graphics & digital soundBitmap = grid of pixels. Vector = list of drawing commands. Sound = analogue wave measured (sampled) atregular intervals.BITMAP8 × 6 pixels · 1 bit eachVECTORellipse(56,42,44,30) line(…)BitmapVectorStored ascolour of every pixelobjects + propertiesResizepixelates / blursscales perfectlyFile sizeresolution × colour depthdepends on object countBest forphotos, scanslogos, fonts, CAD, mapsFormatsBMP, JPEG, PNG, GIFSVG, EPS, AIImage resolution = pixels per inch / total pixels. Colour depth = bits per pixel: 1 bit → 2 colours, 8 bits → 256, 24 bits → 16.7 M.File header stores width, height, colour depth. 2210/9618 both want: file size = W × H × depth (+ header).Sampling sound111100000Sampling rate = samples per second (Hz). CD quality = 44.1 kHz.Sampling resolution = bits per sample (8 levels shown = 3 bits).Higher rate → closer to the analogue wave; higher resolution →finer amplitude steps. Both increase the file size.size = rate × resolution × seconds (× 2 for stereo).Vector = drawing list, bitmap = colour of every pixel — so a vector logo scales cleanly and a bitmap photo does not.cswithzak.com

Bitmap, vector & sound

AS Level 1. Information Representation · O Level 1. Data Representation

ASO Level
Lossless vs lossy compressionWhy compress? Less storage, faster transmission, less bandwidth. The question is whether you can get theoriginal back.LOSSLESSoriginal restored exactly — RLE, ZIP, PNG, FLAC, GIFLOSSYdetail discarded for ever — JPEG, MP3, MP4, AACRun-length encoding (RLE)AAAABBBCCDAA4A3B2C1D2A12 → 10 bytes. RLE wins only with long runs (flat colour areas).Also: LZ (repeated patterns), Huffman (short codes, common symbols).What lossy actually removesImages (JPEG): merge near-identical colours, reduce colour depthor resolution — the eye cannot tell the difference.Sound (MP3): remove frequencies humans cannot hear, quietersounds masked by louder ones; lower sample rate / resolution.Video (MPEG): store only the changes between frames.Result: much smaller files, but quality is permanently lower.LosslessLossyData lost?none — bit-for-bit identical after decompressionyes — cannot recover the originalCompression ratiolower (depends on the data)much higher (adjustable quality)Use whentext, programs, spreadsheets, medical imagesphotos, music, streaming videoExam tip: if the question says “the file must be restored exactly” → lossless; “smallest possible for the web” → lossy.cswithzak.com

Lossless vs lossy compression

AS Level 1. Information Representation · O Level 1. Data Representation

ASO Level

Paper 1 · 2. Communication open topic →

Network topologiesKnow one advantage and one disadvantage of each — and where a single fault stops the network.BUSN1N2N3N4One cable (terminated). Cheap.Collisions; break = whole network down.STARN1N2N3N4N5SWCentral switch. One cable fault isolated.Switch fails = all down; more cable.MESHN1N2N3N4N5Every node linked. Redundant paths.Expensive; complex to manage.Hybrid = mixture (e.g. star-bus). Wireless networks form a star around the access point.Client-server vs peer-to-peer is a separate question from topology.cswithzak.com

Network topologies

AS Level 2. Communication

AS
IP addressing, subnets & DNSIPv4 = 32 bits shown as four denary octets. IPv6 = 128 bits shown as eight hexadecimal groups. DNS mapsnames to addresses.IPv4192.168.1.10110000001010100000000001000010104 octets × 8 bits = 32 bits · each octet 0–255 · ≈ 4.3 billion addresses (2³²) — not enough, hence IPv6 and private ranges.Subnet mask 255.255.255.01s mark the network part, 0s the host part → network ID 192.168.1.0, host 10. Same network ID = same subnet = no router needed.CIDR shorthand: 192.168.1.10/24 (24 network bits). Subnetting splits one network into smaller ones for security and less traffic.IPv62001:0db8:85a3:0000:0000:8a2e:0370:73348 groups × 16 bits = 128 bits, hex. Drop leading zeros; one run of zero groups becomes :: → 2001:db8:85a3::8a2e:370:7334TypeMeaningPublicunique on the internet, allocated by the ISPPrivate10.x · 172.16–31.x · 192.168.x (LAN only, via NAT)Staticfixed — servers, printersDynamicassigned by DHCP each sessionDNS — Domain Name SystemHierarchy of servers: root → .com → cswithzak.comBrowser asks the local DNS server; if unknown it asks upthe chain; the IP is returned and cached for next time.URL = protocol :// domain name / pathcswithzak.com

IP addressing, subnets & DNS

AS Level 2. Communication

AS

Paper 1 · 3. Hardware open topic →

Logic gate symbols & rulesDraw these exactly. A small circle on the output means NOT (inversion).ABXAND1 only if both 1X = A.BABXOR1 if either is 1X = A+BAXNOTinverts the inputX = ĀABXNAND0 only if both 1X = (A.B)‾ABXNOR1 only if both 0X = (A+B)‾ABXXOR1 if inputs differX = A⊕Bcswithzak.com

Logic gate symbols

O Level 10. Boolean Logic · AS Level 3. Hardware

O LevelAS
From logic circuit to truth tableX = (A AND B) OR (NOT C). Work out the intermediate columns first — that is where the marks are.ABCANDNOTORXA AND BNOT CABCA AND BNOT CX000011001000010011011000100011101000110111111101Method1. Inputs: n inputs → 2ⁿ rows, count in binary 000 → 111.2. One column per gate output, left to right through the circuit.3. Final column X is the last gate’s output.4. Expression from circuit: work from inputs to output, bracketing each gate.Writing the expressionX = (A AND B) OR (NOT C)9618 Boolean algebra: X = A.B + C̄NAND/NOR/XOR circuits build the same way.Draw the correct gate shapes, inputs on the left, output on the right; lines that join must have a junction dot.Check: a circuit with 3 inputs must have 8 rows; a truth-table answer with fewer rows loses the mark.cswithzak.com

From logic circuit to truth table

O Level 10. Boolean Logic · AS Level 3. Hardware · A2 Level 15. Hardware and Virtual Machines

O LevelASA2

Paper 1 · 4. Processor Fundamentals open topic →

Two's complement, overflow & shifts8-bit two's complement: the MSB is worth −128. Range −128 … +127. Same bits, different meaning — saywhich you are using.Negating +37 → −37+370010010132 + 4 + 1invert11011010flip every bit (one’s complement)+111011011= −128 + 64 + 16 + 8 + 2 + 1 = −37 ✓Shortcut: from the right, copy up to and including the first 1, then flip the rest.Overflow0111111112700000001+ 110000000= −128 ✗ does not fit in 8 bitsOverflow = the answer needs more bits than the register has.Sign flips: two positives give a negative (or vice-versa).ShiftsShift0001 0110 (22) →logical left 10010 1100 (44)logical right 10000 1011 (11)arithmetic right 1keeps the sign bit1111 0100 (−12) →1111 1010 (−6)Left ×2, right ÷2. Bits shifted out are lost — that isanother cause of overflow. Logical fills with 0s.BCD: each denary digit as its own 4-bit nibble — 47 = 0100 0111. Used where exact decimals matter (currency).cswithzak.com

Two's complement, overflow & shifts

O Level 1. Data Representation · AS Level 1. Information Representation · AS Level 4. Processor Fundamentals

O LevelAS
Von Neumann architectureOne memory holds both instructions and data; CPU and memory talk over three buses.CPUControl Unitdecodes, sends signalsALUarithmetic & logicRegistersPC · MAR · MDR · CIR · ACCCachefast memory for frequently used dataMain memoryRAM — instructions + dataaddress bus →data bus ⇄control bus ⇄Address bus is unidirectional (CPU → memory). Its width sets the maximum addressable memory (n lines → 2ⁿ addresses).cswithzak.com

Von Neumann architecture

O Level 3. Hardware · AS Level 4. Processor Fundamentals

O LevelAS
Fetch – Decode – Execute cycleRegister transfer notation for the fetch stage — learn it word for word.FETCHinstruction from memoryDECODEcontrol unit interprets opcodeEXECUTEALU / registers / memoryrepeat (check for interrupts at the end of each cycle)1. MAR ← [PC]2. PC ← [PC] + 13. MDR ← [[MAR]]4. CIR ← [MDR]address of next instruction → MARincrement ready for the next fetchcontents of that address → MDRcopy the instruction into CIRcswithzak.com

Fetch–Decode–Execute cycle

O Level 3. Hardware · AS Level 4. Processor Fundamentals

O LevelAS
How an interrupt is handledA signal that tells the processor an event needs attention now — without it, the CPU would have to keeppolling every device.SourcesHardwarekey press / mouse clickprinter out of papertimer (time-slice ended)hardware fault, power failureSoftwaredivision by zeroarithmetic overflowillegal / undefined instructiontwo processes need one resource1Device or program raises an interrupt → interrupt flag is set2CPU finishes the current fetch–decode–execute cycle, then tests the flag3Higher priority? Push the registers (PC, ACC, …) onto the stack4Load the ISR (interrupt service routine) address into the PC; run it5Pop the saved registers off the stack; resume the interrupted programPriorities: a low-priority interrupt can itself be interrupted by a higher one (nested); lower ones wait in a queue.The interrupt flag is tested once per cycle — that is why “check for interrupts” is the last step of the FDE cycle.Buffers + interrupts let a slow printer work while the CPU carries on: it interrupts only when its buffer needs refilling.cswithzak.com

How an interrupt is handled

O Level 4. Software · AS Level 4. Processor Fundamentals

O LevelAS
Assembly language & addressing modesInstruction = opcode + operand. The addressing mode says how to interpret the operand. Trace it againstthe memory below.MemoryAddressContents2003002017202930042IX = 2 ACC = ?InstructionModeWhat the operand meansACC ←LDM #200immediatethe number itself200LDD 200directthe contents of address 200300LDI 200indirectaddress 200 holds the address of the value42LDX 200indexedaddress 200 + IX = 202, load its contents9LDR #2immediateload 2 into the index register IXInstruction set you must knowSTO <addr> store ACC ADD/SUB <addr> or #n INC/DEC <reg>CMP <addr> or #n compare with ACC CMI <addr> indirectJMP <addr> jump JPE / JPN <addr> jump if equal / notIN / OUT char ↔ ACC AND / OR / XOR LSL / LSR #n ENDBit manipulation with masksAND #B00001111 → clear the top 4 bits (test / isolate bits)OR #B10000000 → set bit 7 XOR #B11111111 → flip all bitsRelative: operand is an offset from the PC(jump forward/back n instructions).Operands: #n denary, #Bn binary, #&n hex.Labels stand for addresses; the assemblerresolves them via the symbol table.Absolute = a fixed address (direct).Register transfer: MAR ← [PC] · PC ← [PC] + 1 · MDR ← [[MAR]] · CIR ← [MDR]. Square brackets mean “contents of”.cswithzak.com

Assembly language & addressing modes

AS Level 4. Processor Fundamentals

AS

Paper 1 · 5. System Software open topic →

Compiler · Interpreter · AssemblerAll three are translators: they turn what you wrote into machine code the processor can execute.High-level sourceCompilerExecutable file (then run)High-level sourceInterpreterruns each line (as it goes)Assembly (LDA, ADD…)AssemblerMachine code (one-to-one)CompilerInterpreterTranslateswhole program before it runsone statement at a time, while runningErrorsall listed at the end; nothing runsstops at the first error it meetsSpeedfast — already machine codeslower — translated every runSource needed?no: executable can be distributedyes: source + interpreter every timeBest forfinished software, games, appsdeveloping and debuggingHigh-level: portable, English-like, easy to write and debug. Low-level: direct hardware control, fast, machine-specific.IDE: editor, translator, run-time, debugger (breakpoints, single-step, variable watch), auto-complete, pretty-print.cswithzak.com

Compiler, interpreter & assembler

O Level 4. Software · AS Level 5. System Software

O LevelAS
What the operating system doesThe OS is the layer between the hardware and everything else: it hides complexity and shares resourcesbetween programs.HardwareOperating systemUtility & library softwareApplication softwareUserrequests go down the layers; results come back upOS functionsmemory management (allocate, protect, virtual)process management & multitasking (scheduling)file management (names, folders, access rights)hardware / peripheral management (device drivers)security: user accounts, passwords, access levelsuser interface: GUI (icons, windows) or CLIinterrupt handling; error reportingplatform for running application softwareUtility softwaredisk formatter · defragmenter · backupvirus checker · file compressiondisk contents analysis / repairProgram libraries & DLLsLibrary = pre-written, tested routines you can call.DLL (dynamic link library): loaded only at run timeand shared by many programs → smaller executables,fixes reach every program at once; but a missing orchanged DLL breaks the program.O Level: firmware & bootstrapFirmware in ROM runs first, loads the bootstrap, which loads the OSfrom secondary storage into RAM. Then the OS takes over.Exam wording: “the OS manages …” — name the resource (memory, files, devices, processes, users) and what that involves.cswithzak.com

What the operating system does

O Level 4. Software · AS Level 5. System Software

O LevelAS

Paper 1 · 6. Security, Privacy and Data Integrity open topic →

Error detection methodsData can be corrupted by interference during transmission. Each method answers: how is the error found?Parity checkEven parity: number of 1s must be even.1011 0010 → four 1s ✓ (parity bit = bit 8)Fails if two bits flip. A parity block(rows + columns) can locate the bad bit.ChecksumSender adds all bytes, sends the total.Receiver recalculates and compares.Mismatch → request the block again.Cheap; catches most bursts of errors.Echo checkReceiver sends the data straight back.Sender compares it with the original.Weakness: which copy got corrupted?Used with retransmission.Check digitAn extra digit calculated from the other digits (ISBN-13,barcodes: modulo-10 weighting). Recalculated on entry —catches a wrong, missing or transposed digit.ARQ — Automatic Repeat reQuestReceiver checks the data (parity / checksum). Correct →sends ACK. Error, or no ACK before the time-out →the sender automatically retransmits the block.Symmetric encryption: one shared key encrypts and decrypts. Asymmetric: public key encrypts, matching private key decrypts.Encryption protects meaning if data is intercepted — it does not detect errors. Parity, checksum and echo check do.cswithzak.com

Error detection methods

O Level 2. Data Transmission · AS Level 6. Security, Privacy and Data Integrity

O LevelAS
Cyber security: threats vs defencesAim → describe the threat, its effect on the data or user, and the matching prevention. Always pair themup.ThreatWhat happensPrevent it withBrute-forcetrying every possible password until one workslong complex passwords, lock-out, 2FADDoSa botnet floods a server with requests until it failsfirewall, proxy server, traffic filteringHackingunauthorised access to a system to steal or change datafirewall, strong passwords, 2FA, encryptionMalwarevirus, worm, Trojan, spyware, adware, ransomwareanti-malware, updates, backupsPhishingfake email/text lures you to a fake site to enter detailscheck sender & URL, spam filter, awarenessPharmingmalicious code redirects a real URL to a fake websitecheck SSL certificate/padlock, anti-malwareSocial engineeringmanipulating people rather than systems (calls, pretexts)staff training, verify requests, policiesDefence toolkitaccess levelsanti-malwareauthenticationbiometricstwo-factor (2FA)firewallprivacy settingsproxy serverSSL / HTTPSauto-updatesbackupsEncryption makes intercepted data unreadable without the key. Firewall: filters traffic by rules. Proxy: also hides the real server.Virus: needs a host file · Worm: self-replicates across the network · Trojan: hides in legitimate-looking softwareSpyware: records keystrokes · Adware: unwanted adverts · Ransomware: encrypts your files until you paycswithzak.com

Cyber threats vs defences

O Level 5. The Internet and Its Uses · AS Level 6. Security, Privacy and Data Integrity

O LevelAS
Data security · privacy · integrityThree ideas examiners love to see confused: security keeps data safe, privacy keeps it confidential,integrity keeps it correct.SECURITYprotecting data from loss, corruption andunauthorised access• backups & disaster recovery• user accounts, passwords, 2FA• access rights / permissions• firewall, anti-virus, updates• encryption of stored + sent dataPRIVACYkeeping personal data confidential — onlyseen by those entitled• data protection law & policies• privacy settings, consent• anonymising data sets• encryption so intercepted data• cannot be readINTEGRITYdata is accurate, consistent and up todate• validation on input• verification of transfer / entry• referential integrity in a DB• parity / checksum on transmission• no duplicates or contradictionsThreats to computer & datamalware (virus, worm, spyware, ransomware) · hackers · phishing (fake email/site) · pharming (redirect via DNS/host file) · accidental losshardware failure · disaster · disgruntled staff. Match each to a control: backup, access rights, encryption, firewall, anti-malware.Validation checksrange · type · length · format · presenceuniqueness · check digit · limit · consistency(checks data is sensible, NOT that it is true)Verificationon entry: double entry, visual checkduring transfer: parity, checksum, echo check(checks the data was copied/typed correctly)Classic 4-marker: “difference between data security and data integrity” — safe from harm vs correct and consistent.cswithzak.com

Security, privacy & integrity

AS Level 6. Security, Privacy and Data Integrity

AS

Paper 1 · 7. Ethics and Ownership open topic →

Ethics, codes of conduct & software licensingKnow the four licence types with one advantage and one disadvantage each, and apply a professional codeto a scenario.LicenceWhat you getTrade-offCommercialpay first; executable only; restricted copies, no editingsupported, polished · cost, no sourceSharewarefree trial (time or feature limited), then paytry before you buy · nagware, limitedFreewarefree to use, still copyrighted — no source, no resalefree · cannot fix or extend itOpen sourcesource available; run, study, modify, redistribute (GPL, MIT)community fixes · support varies, forksBCS Code of Conduct (4 sections)Public interestProfessional competence & integrityDuty to relevant authorityDuty to the professionACM / IEEE-CS software engineering code (8)1 Public · 2 Client & employer · 3 Product · 4 Judgement5 Management · 6 Profession · 7 Colleagues · 8 SelfApplying it to a scenarioWhich principle is broken? Who is harmed (public, client,colleagues)? What should the professional do instead —refuse, report, disclose, fix, seek advice?Copyright & AI ethicsCopyright protects code, text and images automatically; a licence grants specific permissions. Piracy = using without one.AI ethics: bias in training data, accountability, transparency/explainability, privacy, job displacement, safety of autonomy.Ethical ≠ legal: something can be legal but unethical (and vice-versa). Professional codes set a higher bar than the law.cswithzak.com

Ethics, codes of conduct & licensing

AS Level 7. Ethics and Ownership

AS

Paper 1 · 8. Databases open topic →

Single-table database & SQLField = column (one item of data). Record = row (one entity). Primary key = the field that uniquelyidentifies each record.STUDENTStudentIDNameFormMarkS001Ali10A82S002Hina10B64S003Omar10A91S004Sara10B70StudentID = primary key (unique, never blank).Data types: text, character, Boolean, integer, real, date/time.SELECT Name, MarkFROM STUDENTWHERE Mark >= 70ORDER BY Mark DESC;NameMarkOmar91Ali82Sara70result: 3 records,2 fields, sortedhighest firstAggregatesSELECT COUNT(*) FROM STUDENT WHERE Form = "10A"; → 2SELECT SUM(Mark) FROM STUDENT; → 307ClauseMeaningSELECTwhich fields to show (* = all)FROMwhich tableWHEREcondition: = < > <= >= <> AND ORORDER BYsort: ASC (default) or DESCValidation on fields: range, type, length,format, presence, check digit.Strings in quotes; the semicolon ends the statement.Field names in SELECT are separated by commas.cswithzak.com

Single-table database & SQL

O Level 9. Databases · AS Level 8. Databases

O LevelAS
Entity-relationship diagrams & keysEntity = table. Relationship = how rows are linked. Crow's foot on the “many” side. Many-to-many needs alink entity.One-to-oneEMPLOYEEDESKeach employee has one deskOne-to-manyCUSTOMERORDERone customer places many ordersMany-to-many → resolve with a link entitySTUDENTENROLMENTCOURSEa student takes many courses AND a course has many students → ENROLMENT(StudentID*, CourseID*, Grade) with a composite primary keyKeyMeaningPrimary keyuniquely identifies each tuple (row); cannot be NULLCandidate keyany field (or combination) that could be the primary keySecondary keyindexed field used for fast searching, not uniqueForeign keyprimary key of another table, stored here to make the linkComposite keyprimary key made of two or more fieldsReferential integrity:a foreign key value mustexist as a primary key inthe linked table — noorphan orders.ORDER(OrderID, Date, CustomerID*)Terms: relation = table · tuple = row · attribute = column · degree = no. of attributes · cardinality = no. of tuples.cswithzak.com

Entity-relationship diagrams & keys

AS Level 8. Databases

AS
Normalisation: 1NF → 2NF → 3NFEach step removes one kind of redundancy. Learn the test for each form.UNFrepeating groupsmulti-valued fields1NFatomic valuesno repeating groupsprimary key chosen2NF1NF + no partialdependencies on part ofa composite key3NF2NF + no transitivedependencies(non-key → non-key)Worked example — ORDER(OrderID, CustomerID, CustomerName, ProductID, ProductName, Qty)CustomerName depends on CustomerID, not on OrderID → transitive dependencyCUSTOMER(CustomerID, CustomerName)PRODUCT(ProductID, ProductName)ORDER(OrderID, CustomerID*, ProductID*, Qty)underline PK* = foreign keyBenefits: no update/insert/delete anomalies, less redundancy, smaller storage, consistent data.cswithzak.com

Normalisation 1NF → 3NF

AS Level 8. Databases

AS
SQL: DDL defines the structure, DML works with the dataData Definition Language creates and changes tables. Data Manipulation Language queries and updatesrows.DDLCREATE · ALTER · DROPCREATE DATABASE School;CREATE TABLE Student ( StudentID CHAR(4) NOT NULL, Name VARCHAR(30), DOB DATE, FormID INTEGER, PRIMARY KEY (StudentID), FOREIGN KEY (FormID) REFERENCES Form(FormID) );ALTER TABLE Student ADD Email VARCHAR(50);DMLSELECT · INSERT · UPDATE · DELETESELECT s.Name, f.TutorFROM Student sINNER JOIN Form f ON s.FormID = f.FormIDWHERE s.DOB > '2008-08-31'ORDER BY s.Name;INSERT INTO Student VALUES ('S005','Ali', '2009-02-14', 3);UPDATE Student SET FormID = 4 WHERE …;DELETE FROM Student WHERE StudentID = 'S002';Aggregates & groupingSELECT FormID, COUNT(*), AVG(Mark) FROM Result GROUP BY FormID; SUM · MIN · MAXDBMS features to namedata dictionary (metadata) · data management · query processor · developer interface · security (access rights, views) · backup & recoveryData types in DDL: CHARACTER, VARCHAR(n), BOOLEAN, INTEGER, REAL, DATE. Strings and dates go in single quotes.cswithzak.com

SQL: DDL vs DML

AS Level 8. Databases

AS

Paper 2 · 9. Algorithm Design and Problem-Solving open topic →

Flowchart symbolsUse exactly these shapes. Every decision has two labelled exits; flow lines carry arrows; one START, oneSTOP.TerminatorSTART / STOPProcessTotal ← Total + NInput / OutputINPUT N · OUTPUT TotalDecisionN > 0 ? → Yes / NoSubroutinepredefined process / callflow line (arrow)STARTINPUT NumNum > 0 ?YesOUTPUT "Positive"NoOUTPUT "Not +"STOPProgram development life cycleAnalysisDesignCodingTestingAnalysis (abstraction, decomposition → requirements) · Design (structure diagram, flowchart, pseudocode) · Coding · Testingcswithzak.com

Flowchart symbols & the PDLC

O Level 7. Algorithm Design and Problem-Solving · AS Level 9. Algorithm Design and Problem-Solving

O LevelAS
Stepwise refinement & identifier tables§9.2: plan the identifiers first, then break the problem into steps until each one is a singlepseudocode line. Paper 2 marks the design as well as the code.1 · Problem statementRead 20 marks, count how many are50 or more and output the average.Marks below 0 or above 100 are rejected.2 · Identifier tableIdentifierData typeDescriptionMarkINTEGERone mark, 0–100TotalINTEGERrunning sum of marksPassesINTEGERcount of marks ≥ 50CountINTEGERloop counter 1–20Logic statementsMark >= 0 AND Mark <= 100Mark >= 50Count <= 20Relational (=, <>, <, >, <=, >=) + Boolean (AND, OR, NOT) → TRUE / FALSE3 · Stepwise refinementProcess 20 marks and reportInitialiseTotal, PassesLoop 20×input, check, addReportPasses, Total / 20INPUT MarkIF Mark valid THEN Total ← Total + Mark IF Mark >= 50 THEN Passes ← Passes + 1ELSE OUTPUT "rejected"4 · Pseudocode — sequence · selection · iterationTotal ← 0 : Passes ← 0 // sequenceFOR Count ← 1 TO 20 // iteration INPUT Mark IF Mark >= 0 AND Mark <= 100 THEN // selection Total ← Total + Mark IF Mark >= 50 THEN Passes ← Passes + 1 ENDIF ENDIFNEXT Count : OUTPUT Passes, Total / 20cswithzak.com

Stepwise refinement & identifier tables

AS Level 9. Algorithm Design and Problem-Solving

AS

Paper 2 · 10. Data Types and Structures open topic →

Bubble sort — one pass, step by stepCompare each pair of neighbours; swap if out of order. After pass 1 the biggest is last; after pass n−1everything is sorted.5381compare 5 and 3 → 5 > 3, swap3581compare 5 and 8 → in order, no swap3581compare 8 and 1 → 8 > 1, swap3518end of pass 1: the largest value is now lastPass 2 → 3 1 5 8 · Pass 3 → 1 3 5 8. Each pass needs one fewer comparison. Stop early if a pass makes no swaps.FOR i ← 1 TO N - 1 FOR j ← 1 TO N - i IF A[j] > A[j+1] THEN Temp ← A[j] A[j] ← A[j+1] A[j+1] ← Temp ENDIF NEXT jNEXT iFlag version: REPEAT … Swapped ← FALSE… set TRUE on any swap … UNTIL NOT SwappedLinear search (the other standard algorithm)Found ← FALSE : i ← 1 : WHILE i ≤ N AND NOT Found → IF A[i] = Target THEN Found ← TRUE ELSE i ← i + 1Works on unsorted data; checks every item in the worst case. Binary search (AS) needs sorted data and halves the list each time.Totalling: Total ← Total + Value · Counting: Count ← Count + 1 when true · Max/min: compare with the current bestcswithzak.com

Bubble sort & linear search

O Level 7. Algorithm Design and Problem-Solving · AS Level 10. Data Types and Structures

O LevelAS
Stack · Queue · Linked listKnow the pointers each one needs and what happens on add/remove.STACK (LIFO)739← TopPointerBasePointerPUSH adds at top, POP removes from top.Check full (overflow), empty (underflow).Used for: recursion, interrupts, undo.QUEUE (FIFO)4816FrontRearEnqueue at rear, dequeue at front.Circular queue wraps around with MOD.Used for: print jobs, keyboard buffer, BFS.LINKED LIST1225320StartPointer → node 1 · each node = data + pointer to next · free list holds unused nodesInsert/delete = change pointers only (no shifting). Traversal must start from the head.cswithzak.com

Stack, queue & linked list

AS Level 10. Data Types and Structures · A2 Level 19. Computational Thinking and Problem-Solving

ASA2
Arrays, records & text filesAn array holds many values of ONE type under one name. A record groups DIFFERENT types. A text filekeeps data permanently.1D array — DECLARE Marks : ARRAY[1:5] OF INTEGER[1]72[2]58[3]91[4]64[5]80Marks[3] ← 91 · FOR i ← 1 TO 5 … NEXT i2D array — DECLARE Grid : ARRAY[1:3, 1:4] OF CHAR......X.....row 1row 2row 3col 1col 2col 3col 4Grid[2, 3] ← 'X' // [row, column]Walk it with nested loops: FOR Row … FOR Col … NEXT Col … NEXT RowRecord (composite type)TYPE StudentRec DECLARE Name : STRING DECLARE Mark : INTEGER DECLARE Passed : BOOLEANENDTYPEDECLARE S : StudentRecS.Mark ← 72Text fileOPENFILE "marks.txt" FOR READ // or WRITE / APPENDWHILE NOT EOF("marks.txt") READFILE "marks.txt", Line OUTPUT LineENDWHILECLOSEFILE "marks.txt"WRITEFILE "marks.txt", "Ali,72" // needs FOR WRITEcswithzak.com

Arrays, records & text files

AS Level 10. Data Types and Structures · O Level 8. Programming

ASO Level

Paper 2 · 11. Programming open topic →

Three kinds of loopCount-controlled: you know how many times. Pre-condition: may run 0 times. Post-condition: must run atleast once.Count-controlledFOR … NEXTFOR i ← 1 TO 5 OUTPUT iNEXT iFOR i ← 10 TO 0 STEP -2• known number of repetitions• loop variable set automatically• STEP changes the incrementPre-conditionWHILE … ENDWHILETotal ← 0INPUT NWHILE N <> -1 Total ← Total + N INPUT NENDWHILE• condition tested BEFORE each pass• may run 0 times• sentinel value ends the loopPost-conditionREPEAT … UNTILREPEAT INPUT MarkUNTIL Mark >= 0 AND Mark <= 100// validation loop• condition tested AFTER each pass• always runs at least once• perfect for input validationSelection remindersIF x > 0 THEN … ELSE … ENDIF · CASE OF Choice 1 : … 2 : … OTHERWISE … ENDCASEClose every construct: NEXT · ENDWHILE · UNTIL · ENDIF · ENDCASE. One ENDIF per IF. Indent the body. ← assigns, = compares.Nested loops: the inner loop runs fully for each outer pass (2D array: FOR Row … FOR Col … NEXT Col … NEXT Row).cswithzak.com

Three kinds of loop

O Level 8. Programming · AS Level 11. Programming

O LevelAS
Procedure vs functionBoth are named subroutines with parameters. The difference: a function RETURNS a value, so you use itinside an expression.PROCEDUREPROCEDURE Greet(Name : STRING) OUTPUT "Hello ", NameENDPROCEDURECALL Greet("Ali") // stands alone• does a task (output, update an array…)• called with CALL as a statement• no RETURN value (may change BYREF parameters)FUNCTIONFUNCTION Square(N : INTEGER) RETURNS INTEGER RETURN N * NENDFUNCTIONArea ← Square(5) + 1 // used in an expression• calculates and RETURNS exactly one value• called inside an expression / assignment / OUTPUT• must declare the RETURNS type in the headerParameters & scopeParameter = value passed in via the brackets (Name, N above). Argument = the actual value used in the call (“Ali”, 5).Local: declared inside the subroutine, exists only while it runs. Global: declared at the top, visible everywhere.Why use subroutines? Reuse, easier testing, shorter main program, several people can work on it, easier maintenance.Library routines you must know: MOD, DIV, ROUND, RANDOM (2210) · LENGTH, SUBSTRING/MID, UCASE, LCASE, INT, RAND (9618).cswithzak.com

Procedure vs function

O Level 8. Programming · AS Level 11. Programming

O LevelAS
BYVAL vs BYREF & scopeBYVAL passes a copy — the original is safe. BYREF passes the address — the caller's variable changes. NoBYREF in functions.BYVAL (default)PROCEDURE Inc(BYVAL N : INTEGER) N ← N + 1ENDPROCEDUREX ← 5CALL Inc(X)OUTPUT X // 5X = 5N = 5→6copy — X untouchedBYREFPROCEDURE Inc(BYREF N : INTEGER) N ← N + 1ENDPROCEDUREX ← 5CALL Inc(X)OUTPUT X // 6X = 5→6N ≡ Xsame memory cellWhen to use whichBYVAL: the subroutine only needs to read the value — safe, no side effects.BYREF: the subroutine must send a result back through the parameter (e.g. swap two values, update an array/record).A function returns its answer with RETURN, so it never needs BYREF — the 9618 guide forbids it there.ScopeDECLARE Total : INTEGER // global: seen everywherePROCEDURE P() DECLARE i : INTEGER // localLocal variables exist only while the subroutine runs andare recreated on each call. Prefer locals + parametersover globals: easier to test, reuse and debug.cswithzak.com

BYVAL vs BYREF & scope

AS Level 11. Programming

AS

Paper 2 · 12. Software Development open topic →

Choosing test dataRule under test: “enter a mark from 0 to 100”. Each type of test data has a job — name the type AND saywhy it is chosen.-1050100101accepted range 0 … 100rejectedrejectedTypePurposeExamples hereNormaltypical valid data the program should accept and process23, 50, 87Extremevalid data at the very limits of the accepted range0 and 100Boundaryeither side of each limit: last accepted, first rejected-1 / 0 and 100 / 101Abnormalinvalid (erroneous) data the program must reject-5, 150, “abc”, 3.7Validation: is the data sensible? range · type · length · format · presence · check digit checks.Verification: was it entered correctly? double entry, visual check.Trace table / dry run: one column per variable and the output, one row per change — the way to find logic errors.9618 adds: walkthrough (people read the code), alpha (in-house), beta (real users before release), acceptance (the client signs off).cswithzak.com

Choosing test data

O Level 7. Algorithm Design and Problem-Solving · AS Level 12. Software Development

O LevelAS
Waterfall · iterative · RADThree ways to organise the program development life cycle. Know the shape of each, when it suits, andone strength and weakness.WaterfallAnalysisDesignCodingTestingMaintenanceEach stage finishes before the next starts.+ simple, clear milestones & documents– requirements frozen early; late testing; hard to go backIterativePlanBuildTestReviewrepeatBuild a working version, then improve itin repeated cycles (versions 1, 2, 3…).+ early working software; feedback each cycle– needs good version control; scope creepRAD (rapid application dev.)PrototypeUser feedbackRefineQuick prototypes built with tools,users try them, requirements evolve.+ fast, users involved, fits vague specs– less documentation; inefficient codeDesign tools for any modelStructure chart: hierarchy of modules with parameters ↓ and return values ↑ · State-transition diagram: states as circles, events on arrowsFlowchart · pseudocode · stepwise refinement (break each module into smaller steps until it is codable) · decision tableChoose the model when…Waterfall: clear, fixed requirements (safety-critical) · Iterative: large system delivered in versions · RAD: tight deadline, users on handcswithzak.com

Waterfall, iterative & RAD

AS Level 12. Software Development

AS
Testing, errors & maintenanceTesting finds errors; the type of test says WHO tests WHAT and WHEN. Then classify the error and themaintenance that fixes it.TestWhat it meansWhenStub testingreplace a missing module with a stub that returns a dummy valueduring developmentWhite-boxtester sees the code; every path/branch exerciseddeveloper, unit levelBlack-boxtester sees only inputs/outputs against the specificationany stageIntegrationmodules tested together to check the interfacesafter unit testingAlphain-house testing by the developer's own teambefore releaseBetareal users outside the company try a near-final versionbefore releaseAcceptancethe client checks it meets the requirements and signs offat hand-overError typesSyntaxbreaks the language rules; caught by the translator — missing ENDIFLogicruns, but gives the wrong answer — used > instead of >=; found by test data / trace tableRun-timecrashes while running — division by zero, file not found, array index out of rangeMaintenanceCorrectivefix bugs found after releaseAdaptivenew OS, hardware, law or business rulePerfectivefaster, or features users asked forcswithzak.com

Testing & maintenance

AS Level 12. Software Development

AS

A2 Level

9618

Paper 3 · 13. Data Representation open topic →

Floating-point representationValue = mantissa × 2^exponent, both in two's complement. 8-bit mantissa + 4-bit exponent here; the examgives the sizes.mantissa (8 bits)exponent (4 bits)010110000011sign . 1 1 0 0 0= +31. Mantissa = 0.1011 (binary point after the sign bit) = 0.5 + 0.125 + 0.0625 = 0.68752. Exponent = 0011 = +3 → move the point 3 places right: 0.1011 × 2³ = 101.13. Value = 4 + 1 + 0.5 = 5.5Normalised formPositive mantissa starts 0.1…, negative starts 1.0… — one sign bit,then the first significant bit. Gives maximum precision and a unique form.To normalise: shift the mantissa and adjust the exponent by the samenumber of places (left shift 2 places → exponent − 2).Negative example: 1.0100000 × 2^0010mantissa = −1 + 0.25 = −0.75; × 2² = −3.0. (Check normalised: starts 1.0 ✓)More bits in…gives…mantissaprecision (accuracy)exponentrange (biggest / smallest)neither: fixed totala trade-off — say soErrorsOverflow: result larger than the biggest exponent can express. Underflow: smaller than the smallest — becomes 0.Rounding error: 0.1 (denary) has no exact binary form, so it is truncated/rounded; errors build up over many operations.Never test REAL values with = ; compare the difference with a tolerance instead.cswithzak.com

Floating-point representation

A2 Level 13. Data Representation

A2
File organisation, access & hashingHow records are arranged (organisation) decides how you can get at them (access). Random files hash thekey to an address.SERIALrecords in arrival order (a log)• add: append at the end• find: read from the start until found• use: transaction / temporary filesSEQUENTIALrecords ordered by a key field• add: rewrite the file, or use an overflow area• find: read in order, stop when key passed• use: master files, batch processingRANDOM (direct)address calculated from the key• add: hash the key → address• find: hash again → jump straight there• use: real-time look-ups, indexesAccess methodsSequential access: read records one after another (serial/sequential). Direct access: jump straight to a record (random, or indexed).Hashing — key 4521, file of 100 slotsaddress = 4521 MOD 100 = 21192045212111212223Collision: 1121 MOD 100 is also 21 — slot taken.Fix 1: linear probing — use the next free slot (22).Fix 2: overflow area / linked list from the home slot.Reading: hash, check the key matches, else keep looking.Choosing the organisationHit rate high, whole file processed each run (payroll) → sequential. Individual records needed instantly (bookings) → random.Simple append-only log → serial. Random files waste space if the hash spreads badly; sequential files are slow to update.Pseudocode: OPENFILE f FOR RANDOM · SEEK f, address · GETRECORD f, rec · PUTRECORD f, rec · CLOSEFILE f.cswithzak.com

File organisation & hashing

A2 Level 13. Data Representation

A2

Paper 3 · 14. Communication and Internet Technologies open topic →

Circuit switching vs packet switchingBoth get data from A to B across a network of routers. The difference is whether a path is reservedfirst.Circuit switchingAR1R2R3R4B1. A dedicated end-to-end path is set up before any data is sent.2. Every bit follows the same route, in order, at a guaranteed rate.3. The path is held (and paid for) until the call ends — even if idle.Used for: traditional telephone calls.Packet switchingAR1R2R3R4B1. Data is split into packets, each with a header (addresses, no.).2. Routers forward each packet independently — routes can differ.3. Packets may arrive out of order; re-ordered by packet number.Used for: the internet (IP), email, web, streaming.Circuit switchingPacket switchingSet-uppath reserved first (delay before start)none — send immediatelyReliability / orderguaranteed, in orderpackets can be lost or arrive out of orderEfficiencywastes capacity when idlelinks shared; copes with node failurecswithzak.com

Circuit vs packet switching

A2 Level 14. Communication and Internet Technologies · O Level 2. Data Transmission

A2O Level
TCP/IP protocol stackData moves down the layers when sent (encapsulation) and up when received.ApplicationHTTP · HTTPS · FTP · SMTP · POP3 · IMAP · DNSuser services, dataTransportTCP (reliable, ordered) · UDP (fast, no guarantee)segments, portsInternetIP · routing between networkspackets, IP addressesLink (Network access)Ethernet · Wi-Fi · MAC addressesframes, physical mediasend ↓receive ↑Each layer adds its own header. TCP numbers segments and re-sends lost ones; IP just delivers packets best-effort.cswithzak.com

TCP/IP protocol stack

A2 Level 14. Communication and Internet Technologies

A2
Application-layer protocols & BitTorrentA protocol = agreed rules for communication. Name it, what it carries, and the direction: send = SMTP,receive = POP3/IMAP.ProtocolPurposeDetailHTTP/HTTPSrequest and deliver web pagesS = encrypted with TLS; GET / POSTFTPupload / download files to a serveranonymous or login; separate control + dataSMTPSEND email: client → server, server → serverpush protocol, port 25/587POP3RECEIVE: download mail, delete from serverone device; offline readingIMAPRECEIVE: mail stays on server, folders syncedmany devices; needs connectionThe journey of an emailSenderSender's mail serverRecipient's mail serverRecipientSMTPSMTPPOP3/IMAPBitTorrent — peer-to-peer file sharingTrackerwho has which piecesSeedPeerPeerLeechThe .torrent file points to a tracker. The swarm =all peers sharing the file, in pieces. A seed has thewhole file; a leech downloads without uploading.Pieces are downloaded from many peers at once, thenuploaded to others — the more peers, the faster.No central server; hard to shut down; used legallyfor Linux ISOs and illegally for copyrighted media.cswithzak.com

Application protocols & BitTorrent

A2 Level 14. Communication and Internet Technologies

A2

Paper 3 · 15. Hardware and Virtual Machines open topic →

Half adder & full adderA half adder adds two bits. A full adder adds three (including a carry in) — two half adders plus an ORgate.Half adderABXORS = A ⊕ BANDC = A · BABSC0000011010101101Sum = XOR (1 if inputs differ)Carry = AND (1 only for 1 + 1)1 + 1 = 10₂ → S = 0, C = 1Full adderABCinHalf adder 1Half adder 2S1SC1C2ORCoutABCinSCout0000000110010100110110010101011100111111S = A ⊕ B ⊕ CinCout = A·B + Cin·(A ⊕ B)Chain n full adders,carry rippling along,to add n-bit numbers.Cin of the first = 0.Draw: two XORs feed the sum, the two carries are ORed. Label every wire — examiners mark the connections, not the boxes.cswithzak.com

Half adder & full adder

A2 Level 15. Hardware and Virtual Machines

A2
SR & JK flip-flopsA flip-flop stores one bit. Two cross-coupled NAND gates make an SR flip-flop; the JK adds a clock andhas no invalid state.SR flip-flop (NAND)SRNANDNANDQSRQstate11Qhold (no change)0110SET1001RESET0011invalid — avoidInputs are active-low: a 0 on S sets Q to 1. Q and Q̄ must becomplements; S = R = 0 breaks that rule, and when both returnto 1 the output is unpredictable (race).JK flip-flopJClkKQJKJKQ (next)state00Qhold101SET010RESET11TOGGLE — no invalid stateChanges only on the clock edge (synchronous), so inputs can beset up in advance. Q feeds back to gate J and K — that is whatmakes J = K = 1 toggle and removes the SR invalid state.Flip-flops are built into registers, counters and static RAM. Learn the two truth tables and be able to explain each row.cswithzak.com

SR & JK flip-flops

A2 Level 15. Hardware and Virtual Machines

A2
Karnaugh maps & Boolean algebraGroup 1s in blocks of 1, 2, 4, 8 (edges wrap); each group drops the variable that changes inside it.Bigger groups = simpler.Truth table → K-mapABCX00010010010101111000101011001111A \ BC000111100110110010column order is Gray code: 00 01 11 10 — only one bit changes each stepred (BC = 11, both rows) → B · Cblue (A = 0, BC = 11, 10) → Ā · Bamber (A = 0, BC = 00 & 10, wraps) → Ā · C̄X = B·C + Ā·B + Ā·C̄Boolean algebra lawsLawOR formAND formIdentityA + 0 = AA · 1 = ANullA + 1 = 1A · 0 = 0IdempotentA + A = AA · A = AComplementA + Ā = 1A · Ā = 0AbsorptionA + A·B = AA·(A + B) = ADistributiveA·(B + C) = A·B + A·CA + B·C = (A+B)·(A+C)De Morgan’s laws(A · B)‾ = Ā + B̄(A + B)‾ = Ā · B̄“Break the bar, change the sign.” Use them to convertNAND/NOR expressions and to simplify before drawinga circuit. Every NAND-only circuit relies on them.Sum-of-products: OR together one AND term per group. Check by substituting a truth-table row into your answer.cswithzak.com

Karnaugh maps & Boolean algebra

A2 Level 15. Hardware and Virtual Machines

A2
RISC vs CISC & pipeliningRISC keeps instructions simple and uniform so several can be in the pipeline at once. CISC packs moreinto each one.RISCCISCInstructionsfew, simple, fixed length, one cycle eachmany, complex, variable length, multi-cycleAddressing modesfewmanyRegistersmany general-purposefewerHardwaresimpler processor, hardwired controlcomplex; microcodeCompiler / codemore instructions per programshorter programs, harder compilerPipeliningeasy — uniform instructionsharder5-stage pipeline — 4 instructions in flightcycle 1cycle 2cycle 3cycle 4cycle 5cycle 6cycle 7cycle 8Instr 1FDEMWInstr 2FDEMWInstr 3FDEMWInstr 4FDEMWF fetch · D decode · E execute · M memory access · W write back. No pipeline: 4 × 5 = 20 cycles. Pipelined: 8 cycles.Once full, one instruction completes every cycle. Hazard: a jump or interrupt makes the fetched instructions wrong → flush.Interrupt in a pipeline: finish the instructions already in flight, or flush them and save the state of every stage.cswithzak.com

RISC vs CISC & pipelining

A2 Level 15. Hardware and Virtual Machines

A2
Parallel processing (Flynn) & virtual machinesFlynn's taxonomy classifies computers by how many instruction streams and data streams they handle atonce.SISDsingle instruction, single dataone processor works on one data item at a time — theclassic Von Neumann PCSIMDsingle instruction, multiple dataone instruction applied to many data items at once — GPU,array processor, vector mathsMISDmultiple instruction, single dataseveral processors run different instructions on the samedata — rare; fault-tolerant flight computersMIMDmultiple instruction, multiple datamany processors, each with its own instructions and data —multi-core CPUs, clusters, supercomputersMassively parallel computersThousands of processors, each with its own memory, linked bya fast network, cooperating by message passing. Software mustbe written to split the task — not every problem parallelises(dependencies, communication overhead, cost).Virtual machineGuest OS + appsHypervisor (VM software)Host hardware / host OSsoftware emulation ofa computer: runs anOS in a window, sharingthe real hardwarewith other guestsVM benefitsrun several OSs on one machine · test software safely · isolate untrusted programs · keep legacy systems alivecheaper than many physical servers · easy to copy, snapshot and restoreLimitationsslower — hardware is shared and emulated · needs a lot of RAM/CPU · some hardware not accessible · a host failure takes all guests downMnemonic: the first letter is the instruction stream (S/M), the second is the data stream. SIMD = same op on lots of data.cswithzak.com

Parallel processing & virtual machines

A2 Level 15. Hardware and Virtual Machines

A2
From logic circuit to truth tableX = (A AND B) OR (NOT C). Work out the intermediate columns first — that is where the marks are.ABCANDNOTORXA AND BNOT CABCA AND BNOT CX000011001000010011011000100011101000110111111101Method1. Inputs: n inputs → 2ⁿ rows, count in binary 000 → 111.2. One column per gate output, left to right through the circuit.3. Final column X is the last gate’s output.4. Expression from circuit: work from inputs to output, bracketing each gate.Writing the expressionX = (A AND B) OR (NOT C)9618 Boolean algebra: X = A.B + C̄NAND/NOR/XOR circuits build the same way.Draw the correct gate shapes, inputs on the left, output on the right; lines that join must have a junction dot.Check: a circuit with 3 inputs must have 8 rows; a truth-table answer with fewer rows loses the mark.cswithzak.com

From logic circuit to truth table

O Level 10. Boolean Logic · AS Level 3. Hardware · A2 Level 15. Hardware and Virtual Machines

O LevelASA2

Paper 3 · 16. System Software open topic →

How a compiler translates your codeFour stages — exam questions ask what each stage does and what it produces.Lexical analysissource → tokensstrip whitespace & commentsbuild symbol tableSyntax analysistokens checked against grammar (BNF)parse treesyntax errorsCode generationparse tree → object / machine codeOptimisationremove redundant code, reorder for speed / sizeInterpreter: translates and runs one statement at a time, stops at the first error. Compiler: whole program first.cswithzak.com

Compiler pipeline

A2 Level 16. System Software

A2
Process states & CPU schedulingA process = a program being executed, with its PCB (process control block). The scheduler decides whichREADY process runs next.READYwaiting for the CPURUNNINGusing the CPUBLOCKEDwaiting for I/O / eventdispatched by schedulertime slice ends / pre-emptedwaits for I/OI/O completesnew process admitted ↓finishes → terminatedA RUNNING process cannot go straight to BLOCKED→RUNNING: it must become READY first.Low-level scheduler: READY → RUNNING. High-level scheduler: which jobs are admitted to READY.AlgorithmIdeaFCFSfirst come first served; simpleSJFshortest job first; needs estimatesSRTshortest remaining time; pre-emptiveRound robintime slice each, in turn; fairPriorityhighest first; low may starvePre-emptive = the OS can interrupt a runningprocess (timer interrupt). Non-pre-emptive = itruns until it blocks or finishes.Why multitasking needs interruptsA clock interrupt ends the time slice; the kernel saves the registers in the PCB, picks the next READY process, restores its state.I/O interrupts move BLOCKED processes back to READY. Deadlock: two processes each wait for a resource the other holds.OS purposes: hide hardware complexity, manage resources (CPU, memory, I/O), provide a user interface, run applications.cswithzak.com

Process states & scheduling

A2 Level 16. System Software

A2
Memory management: paging, segmentation & virtual memoryRAM is shared by many processes. The OS maps each process's logical addresses onto physical frames — ordisk when RAM is full.Process (logical pages)page 0page 1page 2page 3Page tablepageframe05122disk37Physical RAM (frames)frame 0: otherframe 1: otherframe 2: P page 1frame 3: otherframe 4: OSframe 5: P page 0frame 6: otherframe 7: P page 3page 2 (swapped out)Disk — page filepage in on demandPagingMemory and process split into fixed-size pages/frames.Any frame will do → no external fragmentation, butthe last page is partly wasted (internal fragmentation).Pages are physical divisions, invisible to the programmer.SegmentationProcess split into variable-size logical segments (code,stack, data). Segment table holds base + limit. Naturalfor sharing/protection, but leaves gaps between segments(external fragmentation).Virtual memoryOnly the pages in use sit in RAM; the rest live in the page file on disk. A page fault loads the missing page,evicting another (page replacement: FIFO, LRU…). Benefit: programs bigger than RAM, more processes at once.Cost: disk is slow — disk thrashing when the OS spends its time swapping pages in and out instead of running code.“Describe how paging works” = pages, frames, page table, logical → physical mapping, swapped to disk when needed.cswithzak.com

Paging, segmentation & virtual memory

A2 Level 16. System Software

A2
BNF, syntax diagrams & Reverse Polish NotationBNF and syntax diagrams define what is legal (syntax analysis). RPN lets a compiler evaluate expressionswith a stack.Backus-Naur Form<digit> ::= 0|1|2|3|4|5|6|7|8|9<unsigned> ::= <digit>|<digit><unsigned><integer> ::= <unsigned>|-<unsigned>::= “is defined as” · | “or” · <…> = non-terminalRecursion (<unsigned> inside itself) allows any length.Syntax diagram for <unsigned>digitloop = one or more digitsCircles = terminals (literal symbols). Rectangles = non-terminals.Follow the arrows; any path through the diagram is valid.Reverse Polish Notation (postfix)(A + B) * C → A B + C *A + B * C → A B C * +Operator after its operands → no brackets or precedence needed.Evaluate 3 4 + 5 * with a stackreadstackaction33push43 4push+7pop 2, add, push57 5push*35pop 2, multiply, pushResult = the one value left on the stack. Convert infix → RPNwith the shunting-yard method or a binary tree (post-order walk).Where this sits in the compilerLexical analysis → tokens · Syntax analysis → parse tree, checked against BNF · Code generation → object code (RPN helps) · Optimisation.Optimisation: remove code that never runs, move loop-invariant calculations out of the loop, reuse computed values, use registers.“Is 123 a valid <integer>?” — walk the rules: 1 is a digit, 23 is an unsigned, so 123 is an unsigned → yes.cswithzak.com

BNF, syntax diagrams & RPN

A2 Level 16. System Software

A2

Paper 3 · 17. Security open topic →

Asymmetric encryption & digital signaturesA key pair: what the PUBLIC key locks only the PRIVATE key unlocks — and vice versa. Which key you usedecides what you achieve.Confidentiality — only the receiver can read itPlaintextEncryptreceiver's PUBLIC keyCiphertextDecryptreceiver's PRIVATE keyAnyone can encrypt with the public key; an eavesdropper who intercepts the ciphertext has no private key, so cannot read it.Authentication — a digital signature proves who sent it and that it was not alteredMessageHash→ digestEncrypt digestsender's PRIVATE keyMessage + signature sentReceiver: 1 decrypts the signature with the sender's PUBLIC key → the original digest. 2 hashes the received message itself.3 compares the two digests. Match → sent by the private-key owner (authentic) and unchanged in transit (integrity). Non-repudiation too.Hashing is one-way: you cannot get the message back from the digest, and a one-bit change gives a completely different digest.SymmetricAsymmetricKeysone shared secret keypublic + private pair per userSpeedfast — used for the bulk dataslow — used to exchange the session keyProblemhow to share the key safelysolved by the public keyCombine them: asymmetric to agree a session key, then symmetric for the traffic — exactly what TLS does.cswithzak.com

Asymmetric encryption & digital signatures

A2 Level 17. Security

A2
Digital certificates & the SSL/TLS handshakeHow can you trust a public key? A certificate authority (CA) signs it. The handshake uses that to set upan encrypted session.Digital certificate• owner / domain name• owner's PUBLIC key• serial number, valid from/to• issuing CA's name• CA's digital signature of the above (hash encrypted with the CA's private key)Browsers ship with trusted CA public keys, so theycan check the CA’s signature and trust the certificate.ClientServer1 hello: TLS version, cipher suites, random2 hello back + the server's certificate3 client verifies the certificate with the CA's public key4 session key, encrypted with the server's PUBLIC key5 server decrypts it with its PRIVATE key; both confirm6 all further traffic: SYMMETRIC encryption with the session keyWhy it mattersHTTPS = HTTP over TLS: the padlock. Preventseavesdropping and tampering, and confirms you aretalking to the real server, not an impostor (pharming).Quantum cryptographyKeys sent as photon states (quantum key distribution). Measuring a photon disturbs it, so any eavesdropper is detected. Needsdedicated fibre, short range, expensive — but immune to the computing power that could break today’s public-key maths.cswithzak.com

Digital certificates & the TLS handshake

A2 Level 17. Security

A2

Paper 3 · 18. Artificial Intelligence open topic →

Graphs & Dijkstra's shortest pathA graph = nodes joined by edges, optionally weighted and directed. Dijkstra finds the cheapest path fromone node to all others.412583ABCDEShortest A → E = A-C-B-D-E, cost 1 + 2 + 5 + 3 = 11 (not the “obvious” A-B-D-E = 12).visitABCDEstart0A041C0319B0318D031811E031811Each step: pick the unvisited node with thesmallest distance, mark it visited, relaxits neighbours: if dist[u] + w < dist[v] thenupdate dist[v] and record u as previous[v].Walk previous[] back from E for the path.Representing a graphABCDEA04100B00050C02080D00003E00000matrix (left): fast lookup, O(n²) spacelist: A → [(B,4),(C,1)] — compact if sparsedirected = arrows; undirected = symmetricA* searchDijkstra + a heuristic h(n) (e.g. straight-linedistance to the goal). Expands the node with thelowest f = g (cost so far) + h. Same answer whenh never over-estimates, but far fewer nodes visited.Uses: sat-nav, packet routing, game path-finding, social graphs. Weighted graphs need Dijkstra; unweighted can use BFS.cswithzak.com

Graphs & Dijkstra's algorithm

A2 Level 18. Artificial Intelligence

A2
Machine learning & neural networksThree ways a program can learn from data instead of fixed rules — plus the network structure and howback-propagation trains it.Supervisedlearns from LABELLED examplesinput → known output;classification (spam?) and regression (price)Unsupervisedfinds structure in UNLABELLED dataclustering customers, anomalydetection, recommendationReinforcementlearns by trial, reward and penaltyagent acts in an environment; gameplaying, robot controlArtificial neural networkinputhiddenhiddenoutputEach node sums weighted inputs, applies an activation function,passes the result on. Weights are the “knowledge”.Deep learning = many hidden layers; needs big data + GPUs.Back-propagation: compare output with the correct answer,compute the error, push it backwards through the layers andnudge every weight to reduce it. Repeat over thousands ofexamples (epochs) until the error is small enough.Regressionfits a line/curve to data so anumeric value can be predicted(house size → price)From a scenario: labelled examples = supervised; grouping unknown data = unsupervised; reward signal = reinforcement.cswithzak.com

Machine learning & neural networks

A2 Level 18. Artificial Intelligence

A2

Paper 4 · 19. Computational Thinking and Problem-Solving open topic →

Stack · Queue · Linked listKnow the pointers each one needs and what happens on add/remove.STACK (LIFO)739← TopPointerBasePointerPUSH adds at top, POP removes from top.Check full (overflow), empty (underflow).Used for: recursion, interrupts, undo.QUEUE (FIFO)4816FrontRearEnqueue at rear, dequeue at front.Circular queue wraps around with MOD.Used for: print jobs, keyboard buffer, BFS.LINKED LIST1225320StartPointer → node 1 · each node = data + pointer to next · free list holds unused nodesInsert/delete = change pointers only (no shifting). Traversal must start from the head.cswithzak.com

Stack, queue & linked list

AS Level 10. Data Types and Structures · A2 Level 19. Computational Thinking and Problem-Solving

ASA2
Recursion: winding & unwindingA recursive routine calls itself. It MUST have a base case (stops) and a general case (moves towards thebase case).FUNCTION Fact(N : INTEGER) RETURNS INTEGER IF N <= 1 THEN RETURN 1 // base ENDIF RETURN N * Fact(N-1) // generalENDFUNCTIONCall stack during Fact(4)Fact(1) → 1Fact(2) → 2 × 1Fact(3) → 3 × 2Fact(4) → 4 × 6← top (last pushed)← bottom (first call)Winding (calls pushed)Fact(4) = 4 × Fact(3)Fact(3) = 3 × Fact(2)Fact(2) = 2 × Fact(1)Fact(1) = 1 ← base caseUnwinding (results returned)Fact(2) = 2 × 1 = 2Fact(3) = 3 × 2 = 6Fact(4) = 4 × 6 = 24Every call pushes a stack frame: parameters, local variables,return address. Nothing is multiplied until the base casereturns — then frames pop and the products build up.No base case → infinite recursion → stack overflow.Recursion vs iterationRecursion: shorter, natural for trees, quicksort, Fibonacci, Towers of Hanoi — but uses stack memory and can be slower.Iteration: a loop with explicit counters — usually faster and memory-safe. Any recursion can be rewritten as a loop with a stack.cswithzak.com

Recursion: winding & unwinding

A2 Level 19. Computational Thinking and Problem-Solving

A2
Big O — how running time grows with nBig O describes the worst-case growth as the input size n gets large; constants and smaller terms areignored.input size n →timeO(1)O(log n)O(n)O(n log n)O(n²)O(2ⁿ)AlgorithmBig Ohash table lookup, array indexO(1)binary searchO(log n)linear search, traversalO(n)merge sort, quicksort (avg)O(n log n)bubble / insertion sortO(n²)brute-force subsetsO(2ⁿ)How to read code: a single loop over n → O(n);a loop inside a loop → O(n²); halving each step→ O(log n); constant work → O(1).Space complexity works the same way for memory.Why it mattersn = 1 000 000: O(log n) ≈ 20 steps, O(n) = 1 000 000, O(n²) = 10¹² — the difference between instant and days.Choosing a sorted array + binary search, or a hash table, is often the whole optimisation.Best / average / worst case can differ (quicksort worst O(n²)); Big O quotes the worst unless told otherwise.Drop constants and lower terms: 3n² + 10n + 7 → O(n²). Nested loops multiply; sequential loops add (and the bigger wins).cswithzak.com

Big O & algorithm performance

A2 Level 19. Computational Thinking and Problem-Solving

A2
Binary search tree, hash table & dictionaryA node = data + left pointer + right pointer. In a BST smaller keys go left, larger go right — soin-order traversal is sorted.50307020406080rootInsert 45: 45 < 50 → left; 45 > 30 → right; 45 > 40 → right → new right child of 40.In-order (left, node, right): 20 30 40 50 60 70 80 — sorted. Pre-order: 50 30 20 40 70 60 80.Post-order: 20 40 30 60 80 70 50. Search is O(log n) if balanced, O(n) if it degenerates into a list.Array implementationidxDataLeftRight150232304537067420005400066000780000 = null pointer · Root = 1 · free-list pointer for empty slotsHash table / dictionarykey → hash function → index"Ali" → 2, "Sara" → 5 …lookup / insert ≈ O(1)collision: two keys, one index→ linear probe, chaining→ rehash when nearly fullDictionary = key:value ADT,usually built on a hash table.Python dict, Java HashMap,VB.NET Dictionary(Of K, V).Traversals in pseudocodePROCEDURE InOrder(P : INTEGER) IF P <> 0 THEN CALL InOrder(Tree[P].Left) // recurse left OUTPUT Tree[P].Data CALL InOrder(Tree[P].Right) // recurse right ENDIFENDPROCEDUREMove the OUTPUT line to the top forpre-order, to the bottom for post-order.Pre-order copies a tree; post-order deletesone safely (children before parent); in-ordergives sorted output from a BST.cswithzak.com

Binary tree & hash table

A2 Level 19. Computational Thinking and Problem-Solving

A2

Paper 4 · 20. Further Programming open topic →

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

OOP: classes, inheritance & polymorphism

A2 Level 20. Further Programming

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

Paradigms, files & exception handling

A2 Level 20. Further Programming

A2
Enroll nowOnline classes