Logic Gates and Number Systems Guide
Logic Gates and Number Systems Guide
Brief Overview
This note covers logic gates and digital circuits and was created from a PDF document. The note covers truth tables, Boolean
expressions, adder circuits, safety system examples, and gate‑level implementation.
Key Points
Understanding basic gate symbols and truth tables
Translating Boolean expressions into circuits
Building half‑adder and full‑adder circuits
Designing real‑world safety circuits with sensors
🔢 Number Systems
1️⃣ Binary (base‑2)
Binary uses only the digits 0 and 1. Each digit is called a bit and corresponds to an ON/OFF switch inside the computer.
Why binary? Computers are built from millions of electronic switches that can be either ON (1) or OFF (0).
Bit groups:
8 bits = 1 byte
4 bits = 1 nybble (used for hexadecimal conversion)
2️⃣ Decimal (base‑10)
Decimal uses the digits 0–9 and is the number system humans use in everyday life.
↔️ Binary ↔ Hexadecimal
1. Group binary digits into sets of four, starting from the right.
2. Pad the leftmost group with leading 0s if it contains fewer than four bits.
3. Replace each 4‑bit group with its hex equivalent using the table above.
Example:
Binary: 1011 1100 0110 → groups 1011 1100 0110 → hex B C 6 → 0xBC6.
Activity 1.3 – Binary → Hexadecimal
Convert these binary numbers to hex:
0
0
1
(Students apply the grouping rule.)
Hexadecimal → Binary
Replace each hex digit with its 4‑bit binary code (use the table).
Example:
Hex 3A7F → binary 0011 1010 0111 1111.
Activity 1.4 – Hexadecimal → Binary
Convert the following hex numbers to binary (list provided in transcript).
↔️ Hexadecimal ↔ Decimal
Hexadecimal → Decimal
1. Write the positional values: … 16 , 16 , 16 , 16 .
3 2 1 0
🧮 Binary Arithmetic
➕ Addition of Binary Numbers
When adding two binary digits:
Bit A Bit B Sum Carry
0 0 0 0
0 1 1 0
1 0 1 0
1 1 0 1 (carry to next column)
Carry propagation works exactly as in decimal addition, but only a single carry (1) can be generated per column.
Example (adding 1011₂ + 1101₂):
1011
+ 1101
-------
11000
Sound
Sampled at a sampling rate (e.g., 44 kHz) and bit depth (e.g., 16 bits).
File size ≈ sampling rate × duration × bit depth ÷ 8 (bytes).
Images
Defined by resolution (pixels width × height) and colour depth (bits per pixel).
Uncompressed file size (bytes) = width × height × bits per pixel ÷ 8.
Lossless compression (e.g., PNG) retains all data; lossy compression (e.g., JPEG) discards some detail to reduce size.
Example from transcript:
A camera captures a 2048 × 2048 image with 24‑bit colour depth.
File size calculation:
Size (bytes) = 2048 × 2048 × 24, /, 8 = 12,582,912 bytes ≈ 12 MiB
Key takeaway: Mastery of binary, decimal, and hexadecimal systems—and the conversion techniques between them—is
foundational for all later topics in computer science, from low‑level hardware design to networking and web development.
Adding three binary digits follows the same rule as two‑digit addition; the column sum can be 0, 1, 2, or 3.
Sum = (column total) mod 2
Carry = ⌊(column total) / 2⌋
Bits added Column total Sum Carry
0+0+0 0 0 0
0+0+1 1 1 0
0+1+1 2 0 1
1+1+1 3 1 1
Quick recap of binary addition (as shown in the transcript):
1. Start at the right‑most column.
2. Add the bits; write the sum bit and carry any overflow to the next column.
3. Continue leftwards, including any incoming carry.
Example – Add 01001010₂ and 00101101₂:
01001010
+ 00101101
----------
01110111 (sum)
^^^^--- carry bits propagated leftwards
Illustrative case – Adding 00111110₂ (62) and 01001100₂ (76) in an 8‑bit register yields 100010010₂. The ninth bit (carry out) indicates
overflow; the stored 8‑bit result (00010010₂ = 18) is incorrect for the intended decimal sum .
62 + 76 = 138
Takeaway: Overflow flags signal that the computed value cannot be represented in the current register width and that a larger register
or signed arithmetic is required.
Left shift (<<) multiplies the unsigned value by 2 (where k is the number of positions).
k
Right shift (>>) divides the unsigned value by 2 , discarding bits that fall off the right end.
k
Positive numbers
Represented exactly as in unsigned binary.
Example: +125 → 01111101₂ (8‑bit).
10
Negative numbers
1. Method A (invert + 1):
Write the magnitude in binary.
Invert every bit (0 ↔ 1).
Add 1 to the inverted pattern.
2. Method B (subtract from 2 ): n
Invert → 11110100₂
Add 1 → 11110101₂
Thus 11110101₂ represents −11 (sign bit 1, value −(128) + 64 + 32 + 16 + 4 + 1 = −11).
Converting back to decimal:
If MSB = 0 → treat as unsigned.
If MSB = 1 → compute the two’s complement again (invert + 1) and apply a negative sign.
Example from transcript: 11001111₂ → invert 00110000₂, add 1 → 00110001₂ (= 49). Therefore the original number is −49 .
Activity 1.12 & 1.13 – Practice converting between decimal and two’s‑complement binary for both positive and negative values.
Extended ASCII adds another 128 codes (128–255) to support additional symbols and non‑English alphabets.
Unicode expands the code space to over a million possible values, allowing representation of virtually every written
language. The first 128 Unicode points coincide with ASCII, ensuring backward compatibility.
Key historical notes (from transcript):
ASCII introduced 1963, revised 1986.
Unicode consortium founded 1991; version 1.0 aimed for a universal, efficient, and unambiguous encoding (16‑bit or 32‑bit).
Case conversion insight: In ASCII, the sixth bit distinguishes upper‑case from lower‑case letters (e.g., A = 01000001₂, a = 01100001₂).
Flipping this bit toggles case, a useful property for simple text processing.
Pros & cons of higher sampling/bit depth (summarised from the transcript):
↑ Sampling / Bit depth Benefit Drawback
Better fidelity (captures more detail) More accurate reproduction of the original Larger file size, higher storage and
sound bandwidth requirements
🖼️ Bitmap Images & Colour Depth 🖥️
Bitmap (raster) images store a matrix of pixels; each pixel’s colour is encoded as a binary value.
Colour depth = bits per pixel → determines how many distinct colours can be represented: 2 bits
colours.
1 bit → 2 colours (black/white)
2 bits → 4 colours
8 bits → 256 colours
24 bits → 2 ≈ 16.7 million colours (true colour)
24
Resolution = width × height (pixels). Larger resolution → more detail but larger file size.
File‑size calculation:
Width×Height×Bits per pixel
Size (bytes) =
Resolution impact: Reducing resolution (fewer pixels) or colour depth (fewer bits per pixel) dramatically cuts storage needs, at the
cost of visual quality—a trade‑off highlighted in the transcript’s discussion of “pixelated” images.
Activity 1.15 – Define terms such as colour depth, bitmap, sampling rate, etc., and explain how varying each affects file size.
Mebibyte MiB 2
20
= 1, 048, 576
Gibibyte GiB 2
30
= 1, 073, 741, 824
Note: Modern RAM/ROM specifications use IEC (binary) units; hard‑disk manufacturers often use decimal units.
2. Audio CD (44.1 kHz, 16‑bit, stereo, 60 min) – already shown above (≈ 606 MiB).
3. Memory‑card capacity question – determine how many 12‑MP (4000 × 3000, 24‑bit) photographs fit on a 6 GiB card by
dividing total bytes available by the per‑photo size.
📉 Compression Techniques 🗜️
🔹 Lossy Compression
Goal: Reduce file size by discarding information perceptually irrelevant to humans.
Audio example: MP3 removes frequencies outside the typical hearing range and merges simultaneous low‑amplitude sounds
(perceptual shaping), achieving ≈ 90 % size reduction.
Image example: JPEG separates luminance from chrominance, downsamples colour information, and applies a discrete
cosine transform to discard high‑frequency components that the eye is less sensitive to.
Result: Smaller files with acceptable quality for most consumer uses; original data cannot be perfectly reconstructed.
🔹 Lossless Compression
Goal: Preserve every original bit; the original file can be perfectly recovered.
Run‑Length Encoding (RLE) – replaces consecutive identical symbols with a count and the symbol.
Text RLE illustration (from transcript):
Original string: aaaaabbbbccddddd (32 bytes) → RLE code 5 97 4 98 2 99 5 100 (8 bytes) → 75 % reduction.
Image RLE example (black‑and‑white 8×8 grid):
Uncompressed: 64 bits (8 bytes).
RLE representation: counts of consecutive white (0) and black (1) runs, e.g., 4 0 3 1 5 0 ... → significantly fewer bytes when
large uniform regions exist.
Limitations: RLE is ineffective for data without long runs (e.g., cdcdcd…), requiring a flag byte (255) to indicate raw data sections, as
demonstrated in the transcript.
Procedure
1. Convert the minuend (A) and subtrahend (B) to binary (same bit‑width).
2. Form the two’s complement of B:
Two’s complement of B = (B ) + 1
01011111
+ 10111100
----------
100110011 (9 bits)
4. Discard the leftmost carry → 00110011 = 51 , which is the correct result 95‑68 = 27 ? (Note: the transcript’s
10
arithmetic appears to contain a typo; the proper two’s‑complement subtraction yields 95‑68 = 27, binary
00011011).
Subtract 49 from 8D (hex).
1. Convert to binary (8‑bit):
0x8D → 10001101
49 → 00110001
2. Two’s complement of 49:
Invert → 11001110
Add 1 → 11001111
3. Add:
10001101
+ 11001111
----------
1 01011100 (9 bits)
Carry out the following binary additions/subtractions using the B‑bit column weighting (where B = 8):
Definition – Cyclic Redundancy Check (CRC) is a checksum computed by counting the number of 1 bits (or using polynomial
division) in the payload and storing the result in the trailer. The receiver recomputes the CRC and compares it; a mismatch indicates
corruption.
Packet Switching
Data is broken into independent packets.
Each packet travels independently through routers, which examine the header to decide the next hop.
Packets may arrive out of order; the sequence numbers in the header allow the receiver to reassemble them correctly.
Advantages (lecture):
No single dedicated line is required; network can reroute around failures.
Efficient use of bandwidth; multiple routes can be exploited simultaneously.
Drawbacks (lecture):
Packets can be lost or delayed, requiring retransmission (ARQ).
Real‑time streams may suffer latency because of reordering and error recovery.
Definition – Skew occurs when bits transmitted in parallel arrive at the receiver at slightly different times, potentially corrupting the
word.
Transmission Modes
Mode Directionality Simultaneity Typical example
Simplex One‑way only No Computer → printer
Half‑duplex Two‑way, but not at the same No Walkie‑talkie
time
Full‑duplex Two‑way simultaneously Yes Telephone line, broadband
internet
Transmission over physical media is prone to interference, packet loss, and skew. Without detection, corrupted data could be
misinterpreted, leading to program crashes or incorrect results.
🔐 Error‑Detection Techniques
Error‑detection methods add extra information to a data block so the receiver can tell whether the block was altered during
transmission.
📏 Parity Checks
Parity – a single extra bit added to a byte (or word) so the total number of 1 bits is either even (even parity) or odd (odd parity).
How it works
1. Sender and receiver agree on even or odd parity.
2. The sender counts the 1 bits in each byte and sets the parity bit (usually the most‑significant bit) to make the total
match the agreed parity.
3. The receiver performs the same count; a mismatch signals a transmission error.
Even vs. odd example
Byte (without parity) # 1 bits Desired parity Parity bit → Final byte
01001101 4 even 0 → 01001101 (already even)
01001101 4 odd 1 → 11001101
Limitation – If two bits are flipped, the overall parity may stay correct, so the error goes undetected.
Activity 2.4 – Find the parity bit for each given byte (use the agreed parity type).
📊 Checksum
Checksum – a numeric value computed from a block of data and transmitted along with that block.
Procedure
1. Both ends agree on an algorithm (e.g., sum of all 16‑bit words modulo 2 ).
16
2. Sender adds all words, reduces the sum to the agreed size, and appends the result as the checksum.
3. Receiver repeats the calculation on the received data.
4. If the two checksums match, the block is assumed error‑free; otherwise a retransmission is requested.
Key point – Unlike a single parity bit, a checksum can detect many multi‑bit errors, though certain patterns (e.g., swapping two
equal‑valued words) may still pass unnoticed.
🔁 Echo Check
Echo check – the receiver sends the entire received block back to the sender, which then compares the echoed copy with the
original.
🔢 Check Digits
Check digit – an extra digit (or character) appended to a numeric identifier that is computed from the other digits.
Positive acknowledgement (ACK) – sent when the receiver finds no error (checksum, CRC, etc., matches).
Negative acknowledgement (NAK) – sent when an error is detected.
Timeout – the sender waits a predefined interval; if no ACK/NAK arrives, it assumes the packet was lost and retransmits.
ARQ variants (Stop‑and‑Wait, Go‑Back‑N, Selective Repeat) differ in how many packets may be “in flight” before an ACK is required.
Mobile‑phone networks heavily rely on ARQ to guarantee data integrity over noisy wireless links.
🔐 Encryption Basics
Encryption transforms plaintext into ciphertext so that an eavesdropper cannot understand the data without the appropriate key.
🔒 Symmetric Encryption
Single secret key is used for both encryption and decryption.
Example from the transcript: a 10‑digit numeric key 136285 causes each character to be shifted by the corresponding digit
(wrap‑around after the alphabet).
Plaintext Shift pattern (1 2 3 …) Ciphertext
C +1 → D D
O +3 → R R
M +6 → S S
… … …
Security note – Brute‑force attacks become infeasible when the key space is large (e.g., 256‑bit keys → 2 256
possibilities).
The main drawback is key distribution: both parties must obtain the same secret securely.
🔑 Asymmetric (Public‑Key) Encryption
Each participant has a public key (shareable) and a private key (kept secret).
Data encrypted with the recipient’s public key can only be decrypted with the matching private key.
The diagram below illustrates a simple public‑key scenario with four users (Tom, Susan, Mike, Megan) each sharing their public keys
with Jane, while Jane’s private key remains undisclosed.
The image shows arrows from each user’s public key to Jane, emphasizing that public keys are freely distributed, whereas the private
key stays hidden.
Advantages – No need to exchange a secret key beforehand; suitable for large, open networks.
Typical use – Exchange of a symmetric session key (which then encrypts the bulk data), combining the speed of symmetric
encryption with the key‑distribution strengths of asymmetric cryptography.
📋 Quick Comparison
Feature Symmetric Encryption Asymmetric Encryption
Key count 1 (shared) 2 (public + private)
Speed Fast (hardware‑friendly) Slower (large‑integer ops)
Key distribution Problematic (must be secret) Easy (public keys can be broadcast)
Typical role Bulk data protection Secure key exchange, digital signatures
🧩 Practice Activities
Activity Goal Hint
2.4 Compute parity bits for a list of bytes. Remember the agreed parity type.
2.5 Identify which received bytes indicate an Parity alone can’t pinpoint the exact bit
error and locate the flipped bit (if when only one error is present.
possible).
2.6 Given a 2‑D parity block (odd or even), Use both horizontal and vertical parity
locate and correct the single corrupted bit. checks.
2.7 Generate ISBN‑13 and Modulo‑11 check Follow the step‑by‑step algorithms
digits for supplied numbers. described above.
2.8 Explain why Jane can receive encrypted Relate to the public‑key encryption flow.
documents from anyone but can only send
encrypted documents back to those who
know her public key.
2.9 Match terminology (ciphertext, plaintext, Review the block‑quotes for concise
checksum, ARQ, etc.) to definitions. definitions.
These activities reinforce the concepts of error detection, correction, and basic encryption introduced in this section.
Receiver operation – computes the parity of the received byte, compares it to the expected parity, and if they differ
requests a retransmission.
Check‑digit workflow (human‑operator entry):
1. Operator types the numerical code.
2. Computer calculates the check digit from the entered digits.
3. Calculated digit is appended to the code and compared with the digit typed by the operator.
4. If the two check digits differ, the operator is prompted to re‑enter the code.
Check‑digit – a numeric value derived from the other digits of a code that validates the entry; common in ISBN, VIN, etc.
🔐 Encryption Basics
Symmetric Encryption
Symmetric encryption uses a single secret key for both encryption and decryption.
Example from lecture: a 6‑digit numeric key 136285 shifts each plaintext character by the corresponding digit (wrapping
around the alphabet).
Pros – fast, suitable for bulk data.
Cons – key distribution is difficult; both parties must obtain the same secret securely.
Asymmetric Encryption
Asymmetric (public‑key) encryption employs a public key (shared openly) and a private key (kept secret).
Data encrypted with a recipient’s public key can only be decrypted with the matching private key.
Typical use: exchange a symmetric session key, then use the faster symmetric algorithm for the actual data.
The diagram shows four users each sharing their public keys with Jane; only Jane’s private key can decrypt messages encrypted with
her public key.
Skew – timing mismatch between parallel lines that can corrupt data if bits arrive at different times.
Core components:
Component Role
Control Unit (CU) Fetches, decodes, and orchestrates execution of
instructions.
Arithmetic Logic Unit (ALU) Performs arithmetic (add, subtract, shift) and logical (AND,
OR) operations.
Registers Fast, small storage inside the CPU (e.g., Program Counter,
MAR, MDR, Accumulator).
System Clock Generates timing signals that synchronize all internal
operations.
Instruction cycle – Fetch → Decode → Execute (see later section).
⏱️ Performance Factors
1. Clock speed – higher frequency (GHz) yields more cycles per second, but only benefits operations that can complete within
a cycle.
2. Bus width – wider address/data buses move larger words per cycle, reducing the number of cycles needed for large
transfers.
3. Cache memory – a small, fast SRAM inside the CPU that stores frequently accessed data/instructions; reduces latency
compared with main RAM.
4. Multi‑core CPUs – multiple ALU‑CU‑register sets on a single die; parallelism improves throughput, though inter‑core
communication overhead can limit scaling.
Each instruction consists of an opcode (specifies the operation) and optional operands (data or addresses).
Example architecture: x86 – used by Intel Pentium, AMD Athlon, and most modern PCs.
Note: High‑level programming languages are compiled or interpreted into these binary instructions, which then traverse the
fetch‑decode‑execute cycle.
🤖 Embedded Systems
Embedded system – a dedicated computer that performs a specific set of tasks within a larger device.
Typical components: microcontroller (CPU + memory + peripherals), sensors, actuators, and often non‑volatile storage
(SSD).
Characteristics: real‑time operation, low power, compact size, may be programmable (firmware updates) or fixed‑function.
The flowchart shows the central “Set‑top box controller” exchanging data with the front end, RAM, interface, SSD, and front panel.
Remote signals and manual inputs feed into the front panel, illustrating how user commands travel through the embedded system.
Security System Example
Sensors (temperature, pressure, acoustic) and a keypad interface provide inputs to the “Security system controller,” which consults
stored settings in SSD/RAM and drives outputs such as alarms or notifications.
Other Embedded Applications
Application Typical Inputs Typical Outputs
Lighting control Light sensors, time‑of‑day, occupancy Dimmed LEDs, automated on/off
detectors
Vending machine Keypad selections, coin sensors, Motor actuation (product dispense), LCD
temperature sensor display, remote sales reporting
White‑goods (washer, fridge, oven) Knob/ touch input, temperature sensors Motor control, heating elements, status
LEDs
Automotive ECU Engine speed, fuel pressure, oxygen Fuel injection timing, spark timing,
sensor diagnostic messages
Structure
Each decimal digit is encoded by four elements (2 dark, 2 light).
Left‑hand side digits: odd number of dark elements, start with a light bar.
Right‑hand side digits: even number of dark elements, start with a dark bar.
This mirrored layout lets the scanner read the code in either direction.
Scanning process
1. A red LED (or laser) emits light onto the barcode.
2. Dark bars reflect little light; light bars reflect more.
3. Photo‑electric sensors convert the reflected light into a binary stream.
4. The stream is decoded into the original numeric value (e.g., digit ‘3’ → pattern DDDDED → binary 0110).
Typical use in retail
Barcode value is looked up in the stock database; the record supplies price, description, and current inventory.
After a sale the inventory count is decremented; automatic re‑order flags fire when stock falls below a threshold.
Image‑capture pipeline
1. Light passes through the lens onto a sensor array of millions of photodiodes (pixels).
2. Each pixel generates an electric charge proportional to incident light intensity.
3. An analog‑to‑digital converter (ADC) quantises the charge; an 8‑bit ADC yields 2 = 256 brightness levels per
8
channel.
4. Most cameras record 24‑bit RGB (8 bits per colour), so a single pixel is represented as three bytes (e.g., orange =
R = 215, G = 165, B = 40 → binary 11010111, 10100101, 00101000).
File‑size estimate
width×height×bits per pixel
Size (bytes) =
8
Example: a 4000 × 3000 sensor at 24‑bit depth → 4000 × 3000 × 24/8 = 36, 000, 000 bytes ≈ 34 MiB.
Embedded functions – auto‑focus, shutter‑speed control, flash timing, red‑eye reduction, aperture adjustment, etc., all
driven by firmware on the camera’s microcontroller.
The DSLR shown uses a large zoom lens; the image sensor beneath the lens converts the optical scene into a digital pixel array.
⌨️ Input Devices
Keyboard
Keyboard – a matrix of mechanical (or capacitive) switches that generate ASCII/Unicode codes for each pressed key.
Scanning circuit – pressing a key completes a circuit on the keyboard’s PCB; a microcontroller reads the row/column matrix,
maps the contact to an ASCII value, and sends the code to the host via USB or wireless (Bluetooth).
Ergonomic variants – split or curved layouts reduce repetitive‑strain injury (RSI).
Microphone
Microphone – a transducer that converts acoustic pressure variations into an electrical signal.
Optical mouse – a pointing device that tracks motion by capturing successive images of the surface with a tiny CMOS sensor.
How it works
An infrared LED illuminates the surface.
The CMOS sensor takes ~1500 images / s; a digital signal processor (DSP) compares consecutive frames to
compute X/Y displacement.
No moving parts → no mechanical wear, works on most textures.
Touch Screens
Touch screen – a display that can sense the location of a finger or stylus contact.
📠 Scanners
2‑D Document Scanners
2‑D scanner – an optical device that converts a physical page into a digital image.
The diagram walks through the four main stages of scanning a document, from placement to digital conversion.
OCR (Optical Character Recognition) transforms the bitmap into editable text, enabling data entry automation (e.g.,
passport scanning at airports).
3‑D Scanners
3‑D scanner – captures the shape of a solid object by sampling points in three‑dimensional space.
📺 Output Devices
Actuators
Actuator – a device that converts an electrical control signal into physical motion.
Solenoid (linear) – coil generates a magnetic field when energized, pulling a plunger.
Rotary solenoid – similar coil drives a rotating arm.
Used to control valves, conveyor belts, and other electromechanical mechanisms.
Light Projectors
Type Core technology Colour generation Typical resolution Notable pros Notable cons
Digital Light Micromirror array White light split by Determined by High contrast, fast Visible rainbow
Processing (DLP) (DMD) tilts ± ± to colour wheel or micromirror count switching effect with some
direct light RGB LEDs colour wheels
LCD projector Three LCD panels White light passes Dependent on Accurate colour Lower contrast,
(R, G, B) modulate through LCD panels panel pixel count reproduction requires more
light that block/ transmit alignment
colour
DLP operation – each micromirror represents one pixel; “on” mirrors reflect light into the lens, “off” mirrors divert it away.
Rapid toggling creates grey levels (e.g., 1024 shades).
LCD operation – a bright white source passes through three colour‑filtered LCD panels; each panel blocks or transmits its
colour component, producing a full‑colour image after recombination via a prism.
QR code – two‑dimensional matrix barcode capable of storing thousands of characters with built‑in error correction.
CCD (Charge‑Coupled Device) – light‑sensitive sensor that converts photons into charge packets for imaging.
ADC (Analog‑to‑Digital Converter) – device that maps a continuous voltage into a discrete digital value (e.g., 8‑bit → 256 levels).
OCR (Optical Character Recognition) – software that interprets scanned bitmap text into editable characters.
Solenoid – electromechanical actuator that produces linear motion when its coil is energized.
DMD (Digital Micromirror Device) – array of tiny tilting mirrors used in DLP projectors to modulate light.
Capacitive touch – detection of a finger‑induced change in an electrostatic field across a conductive layer.
Resistive touch – detection of voltage change when two conductive layers are pressed together.
These notes expand on the earlier sections on number systems, binary arithmetic, and data representation, showing how the underlying
binary and hexadecimal concepts are applied in real‑world hardware such as barcodes, digital imaging sensors, input peripherals, and
visual output devices.
🖨️ Inkjet & Laser Printers
🟢 Inkjet printer – how it works
Inkjet printer – a device that creates text or images by propelling tiny droplets of liquid ink onto paper.
Core components
Print head with an array of nozzles (one per colour).
Ink cartridges – either a single tri‑colour cartridge (cyan, magenta, yellow) plus a black cartridge, or separate
cartridges for each colour (some models use six colours).
Stepper motor & belt – moves the print head horizontally across the page.
Paper feed mechanism – automatically pulls paper from the tray; a sensor detects paper presence and jams.
Droplet‑generation technologies
1. Thermal‑bubble – a resistor heats a tiny volume of ink, creating a vapor bubble that pushes a droplet out. When
the bubble collapses, a vacuum draws fresh ink into the nozzle.
2. Piezoelectric – a crystal behind each nozzle flexes when an electric pulse is applied, forcing a droplet forward
while simultaneously refilling the chamber.
Printing sequence (common to both technologies)
Stage Action (as discussed)
1️⃣ Document data is sent to the printer driver.
2️⃣ Driver formats the data for the specific printer and checks
availability (busy, offline, out‑of‑ink).
3️⃣ Formatted data is stored in a printer buffer (temporary
memory).
4️⃣ Paper is fed; a sensor confirms paper presence (error if jammed
or empty).
5️⃣ The print head scans side‑to‑side, spraying the four ink colours in
precise amounts to build the desired colour at each pixel.
6️⃣ After each line, the paper advances slightly for the next pass.
7️⃣ Steps 5‑6 repeat until the page is complete.
8️⃣ If buffer still contains data, the cycle returns to step 5.
9️⃣ When the buffer empties, the printer sends an interrupt to the
host CPU requesting more data. The loop continues until the
whole document is printed.
Additive vs. subtractive – traditional manufacturing removes material (e.g., CNC milling). 3D printing adds material, enabling
complex geometries with less waste.
Major 3D‑printing techniques
Technique Core principle Typical material
Binder jetting A print head deposits a liquid binder onto Powdered metal, sand, ceramic
a thin powder layer; the binder solidifies
the powder into a slice of the object.
Direct inkjet (material jetting) Ink‑jet heads extrude photopolymers or Photopolymer resin, wax
waxes; each deposited droplet cures (UV)
or solidifies.
Laser sintering / melting A high‑power laser fuses powder particles Nylon, metal powders
together where the part cross‑section
resides.
Stereolithography (SLA) A UV laser (or projector) cures a vat of Photopolymer resin
photosensitive resin point‑by‑point.
📺 Display Technologies
💡 LED screens
LED screen – a matrix of tiny Light‑Emitting Diodes that generate light directly; each LED can be individually driven to produce
varying brightness.
Used for outdoor advertising because of high brightness and long life.
Modern “LED‑backlit LCD” panels actually employ a thin array of blue‑white LEDs behind an LCD panel (see next section).
🖥️ LCD screens
LCD (Liquid‑Crystal Display) – a panel of liquid‑crystal cells whose orientation changes under an applied electric field, modulating
light from a backlight source.
Back‑lighting options
CCFL (cold‑cathode fluorescent lamp) – older technology, yellowish hue.
LED back‑light – newer, instant full brightness, whiter light, thinner panels, lower power.
Advantage of LED back‑lighting Reason
Immediate full brightness No warm‑up time like CCFL
Better colour fidelity Whiter light improves colour rendering
Lower power consumption LEDs are more efficient
Thinner design Small LED arrays replace bulky tubes
🌈 OLED screens
OLED (Organic Light‑Emitting Diode) – a display where each pixel contains an organic emissive layer that produces light when an
electric field is applied; no separate back‑light is needed.
Structure (simplified):
1. Glass or plastic anode (positive).
2. Conductive layer.
3. Emissive organic layer (light‑emitting).
4. Metal cathode (negative).
When voltage is applied, electrons and holes recombine in the emissive layer, emitting photons directly from the pixel.
Key benefits
Benefit Explanation
Ultra‑thin & flexible Entire stack can be built on plastic substrates; enables foldable
or curved screens.
True black & high contrast Pixels can be turned completely off, eliminating back‑light bleed.
Low power for dark images No back‑light to power when displaying black.
Wide viewing angles (~170°) Light is emitted directly from each pixel.
The curved monitor illustration shows how OLED’s flexibility permits wrap‑around designs, opening possibilities for wearable or
“watch‑strap” displays.
Signal chain
1. Digital audio (e.g., a music file) → DAC (Digital‑to‑Analog Converter) creates an analogue voltage waveform.
2. Amplifier boosts the voltage/current to a level capable of driving the speaker coil.
3. Voice coil (wire wound around an iron core) receives the amplified current, generating a magnetic field that
interacts with the permanent magnet.
4. The resulting force moves the cone (paper, plastic, or synthetic material), pushing air and producing sound.
The diagram visualises how the coil’s varying magnetic field drives the cone, converting electrical energy into acoustic waves.
⚙️ Actuator definition
Actuator – an output device that receives a control signal (often digital) and produces a physical effect (movement, heat, light, etc.).
Common actuators
Solenoid – linear motion when coil is energised.
Stepper motor – precise angular steps for positioning (e.g., printer head).
Servo motor – closed‑loop position control.
Heater element – converts electrical power into heat (used in central heating).
Valve – opens/closes fluid flow under electronic command.
These sections build directly on the earlier binary‑data and hardware fundamentals, showing how low‑level representations (bits, bytes,
colour depth) are turned into concrete devices—printers, 3‑D fabricators, displays, audio output, and intelligent sensing‑control loops.
Actuator: a device that receives an electrical command and produces a physical effect (heating, valve movement, motor rotation).
ADC (Analog‑to‑Digital Converter): samples an analog sensor voltage, quantises it and delivers a binary value to the CPU.
DAC (Digital‑to‑Analog Converter): converts a digital control word from the CPU back into an analog voltage or current that drives
an actuator.
Control logic: the CPU compares each digital sensor value with its stored set‑point. If the reading deviates, the appropriate actuator
is driven via a DAC output.
Control: active adjustment of actuators based on sensor feedback, forming a closed‑loop system.
🧠 Primary Memory
Random‑Access Memory (RAM)
RAM: a volatile memory where each cell can be read or written in any order; contents disappear when power is removed.
Key properties:
Random access – any address can be reached without regard to previous accesses.
Read/Write – both operations are supported.
Volatile – data lost on power‑off.
Larger RAM → fewer page‑faults and higher overall system performance.
Read‑Only Memory (ROM)
ROM: a non‑volatile memory that is programmed once (or a few times) and thereafter only read.
Typical uses: BIOS/UEFI firmware, factory‑programmed microcontroller code, lookup tables that never change at runtime.
Feature RAM ROM
Volatility Volatile Non‑volatile
Write capability Yes (dynamic) No (or limited)
Typical role Working data, program execution Startup code, fixed constants
📚 Types of RAM
Type Cell structure Refresh requirement Typical access time Common use
DRAM (Dynamic) Capacitor + access Yes – every ~15 µs ~60 ns Main system memory
transistor (high density, low cost)
SRAM (Static) Flip‑flop (four No ~25 ns CPU cache, registers
transistors) (fast, low density, higher
cost)
DRAM stores each bit as a charge on a tiny capacitor; periodic refresh cycles are mandatory to prevent leakage.
SRAM retains its state as long as power is present, eliminating refresh overhead and providing faster access, which is why it
is preferred for cache memory.
📦 Secondary Storage
Hard Disk Drive (HDD)
Structure: one or more rotating platters coated with magnetic material; read/write heads hover nanometers above the
surface.
Latency: time for the desired sector to rotate under the head; plus seek time for head movement.
Fragmentation: repeated write/delete cycles scatter a file across non‑contiguous sectors, degrading performance;
defragmentation re‑orders sectors to improve sequential reads.
🖥️ Virtual Memory
Virtual memory: an OS technique that treats a portion of secondary storage (typically a HDD or SSD) as an extension of RAM,
allowing programs to use more address space than physically available.
Paging moves fixed‑size blocks (“pages”) between RAM and the swap file.
Thrashing occurs when the system spends more time swapping pages than executing useful work, dramatically reducing
performance.
Mitigation strategies: increase RAM, reduce the number of active processes, lower the swap file size, or replace an HDD with
an SSD to speed up page‑in/page‑out operations.
☁️ Cloud Storage
Model Ownership Typical location Example use case
Public cloud Third‑party provider Shared data centre Consumer backup, SaaS
Private cloud Organization itself On‑premises or dedicated Sensitive corporate data
hosted
Hybrid cloud Combination Both on‑premises and public Burst capacity for peak loads
Security note: When data reside off‑site, organisations must evaluate the provider’s physical safeguards, disaster‑recovery plans,
and staff access controls. High‑profile breaches (e.g., XEN hypervisor incident, celebrity photo leaks, Mexican voter‑registry hack)
illustrate the importance of robust encryption and multi‑factor authentication.
In the transcript, Program 2, Program 3, and Program 4 together occupy the full 32 GiB of RAM.
By allocating part of the hard‑disk (or SSD) as swap space, the operating system can page out inactive memory pages,
freeing RAM for Program 5.
The paging process:
1. Identify a rarely‑used page in RAM.
2. Write the page to the swap file (on SSD/HDD).
3. Mark the RAM frame as free.
4. Load the needed page for Program 5 into the freed frame.
Because SSDs have much lower latency than HDDs, using an SSD for swap improves performance compared with a
mechanical drive.
Term Definition
Swap space Disk area reserved for paging out memory pages when RAM is
full.
SSD (Solid‑State Drive) Non‑volatile storage using NAND flash cells; no moving parts.
HDD (Hard‑Disk Drive) Magnetic platter‑based storage; data written/read by a moving
head.
Virtual memory Technique that treats part of secondary storage as an extension
of RAM.
Reserved storage Portion of a storage device set aside for system use (e.g., OS,
swap).
Solid‑state devices control the movement within a cell. The device is made up of transistor + floating‑gate structures. When a
program voltage is applied, electrons are trapped on the floating gate, raising the threshold voltage and representing a binary “1”. An
erase operation removes the electrons, returning the cell to “0”. Cells are organized into pages, which group into larger blocks. A
dedicated controller manages wear‑leveling, error‑correction, and the mapping of logical addresses to physical pages.
1. Fast random‑access – no seek time, leading to near‑instant boot and app launch.
2. Lower power consumption – fewer moving parts, extending battery life.
3. Shock resistance – solid‑state cells survive drops and vibrations better than spinning platters.
Disadvantage:
Limited write endurance – each NAND cell can endure only a finite number of program/erase cycles, which can shorten the
drive’s lifespan under heavy write workloads.
Part Meaning
First 24 bits (first three octets) Organizationally Unique Identifier (OUI) – identifies the
manufacturer (e.g., Apple).
Last 24 bits (last three octets) Device serial number – unique to that NIC.
Changing a MAC to an LAA can cause address collisions if the new value is not unique on the local segment.
Routers translate between network protocols, inspect the packet header, and forward the frame to the appropriate switch
using the destination MAC address.
If the MAC address does not match any device on the current LAN, the router forwards the frame to another switch until the
correct endpoint is reached.
Image – Basic LAN‑to‑Internet Diagram
The diagram shows three computers and a server on a LAN, a switch, a router, and the cloud representing the Internet. The router
serves as the gateway, performing NAT for the private IPs and directing outbound traffic to the Internet.
Routers can be wired (Ethernet ports) or wireless (integrated Wi‑Fi).
They also often include a built‑in firewall that filters inbound traffic based on rules.
Detection – When a USB device is plugged in, a voltage change on the D+ / D‑ lines signals the host, which then loads the
appropriate driver.
Standards – USB 2.0 (480 Mbps), USB 3.0/3.1 (5–10 Gbps), USB‑C (reversible connector, up to 20 Gbps).
📡 Wireless Technologies
Wi‑Fi – Designed for full‑scale networks; offers higher data rates, greater range, and robust security (WPA3).
Bluetooth – Short‑range (≤ 10 m), low‑power; uses frequency‑hopping spread spectrum to minimise interference; ideal for
peripheral devices (headsets, keyboards).
Frequency Band Typical Use Approx. Frequency
2.4 GHz (Bluetooth, Wi‑Fi b/g/n) General consumer devices 2.4 GHz
5 GHz (Wi‑Fi a/n/ac/ax) High‑speed indoor networking 5 GHz
60 GHz (Wi‑Gig) Multi‑gigabit short‑range links 60 GHz
📊 Summary Tables
MAC vs. IP Address Characteristics
Property MAC Address IP Address
Layer Data Link (Layer 2) Network (Layer 3)
Format 48 bits, six hex octets IPv4: 32 bits dotted decimal; IPv6: 128 bits
colon‑hex
Scope Local‑segment uniqueness Global (public) or local (private)
uniqueness
Assignment Factory‑burned (UAA) or locally set (LAA) Static (manual) or dynamic (DHCP)
Changeability Can be spoofed (LAA) Can change with lease renewal (dynamic)
The diagram shows the central “SYSTEM SOFTWARE” node with six branches: Compilers, Linkers, Device Drivers, Utilities, and
Operating Systems (O/S). Each box is colour‑coded and briefly describes the role of the component, illustrating how they together
make a computer usable.
🛠️ Utility Software
Utility programs are optional tools bundled with the operating system that help maintain, optimise, or protect the computer.
🦠 Virus Checkers
An antivirus program runs in the background, scanning files before they are executed and periodically performing full‑system scans.
Key features:
Feature Description
Signature database Stores known virus patterns; files are compared against it.
Heuristic analysis Looks for suspicious behaviour that may indicate a new,
unknown virus.
Quarantine Infected files are isolated, allowing the user to delete or restore
them.
Automatic updates New virus definitions are downloaded regularly to keep
protection current.
Scheduled full scans Recommended weekly to catch dormant threats.
Best practice: keep the antivirus up‑to‑date and run regular full scans, because new malware appears constantly.
📂 Disk Defragmentation
Defragmentation rearranges fragmented file blocks on a hard‑disk drive (HDD) so that each file occupies a contiguous set of
sectors, reducing head‑movement time.
💾 Backup Software
Backup utilities create duplicate copies of important data to protect against loss.
� screensavers
Screensavers originally prevented phosphor burn‑in on CRT monitors by periodically refreshing the display with moving images.
Modern LCD/OLED screens do not need this, but screensavers still serve two purposes:
Security lock – after inactivity the screen locks, requiring a password to resume.
Background tasks – some screensavers trigger distributed‑computing projects or other idle‑time processing.
🔧 Device Drivers
Device drivers translate OS commands into a format the peripheral hardware can understand.
Key points:
Drivers contain descriptors (VID, PID, serial number) that let the OS identify the device.
Without the correct driver, a plugged‑in device (e.g., USB flash drive, printer, camera) remains invisible to the system.
Serial numbers must be unique; duplicate IDs can cause conflicts when two identical devices are connected simultaneously.
The OS sits between the CPU and user applications (Spreadsheet, Email, Web browser, anti‑virus). Blue arrows indicate how each
application sends requests to the OS, which then coordinates with the CPU (green dotted lines).
Typical OS responsibilities:
Human‑Computer Interface (HCI) – CLI or GUI.
Security management – log‑on, passwords, access control.
Interrupt handling – respond to hardware and software signals.
Platform for running routines – load and execute application code.
Memory management – allocate RAM, swap pages, protect address spaces.
Hardware peripheral management – via device drivers.
File management – directory structures, permissions, I/O buffering.
Common OS families: Microsoft Windows, Apple macOS, Linux, Android, iOS.
🧠 Memory Management
The OS allocates RAM to running processes, ensures no two processes share the same address space, and moves inactive pages to
secondary storage (virtual memory).
🔐 Security Management
Security management guarantees integrity, confidentiality, and availability of data.
Mechanisms include:
Regular OS and application updates (patches).
Antivirus/antispyware (kept current).
Firewalls (monitor inbound/outbound traffic).
User accounts & privileges (passwords, UID/GID).
Encryption/decryption for data in transit or at rest.
📁 File Management
File management handles naming, creation, deletion, copying, moving, and permission enforcement.
Key tasks:
Naming conventions (e.g., [Link], [Link]).
Directory hierarchy – organizing files into folders.
Access control – read/write/execute rights, file locking.
Memory allocation – loading file contents from storage into RAM for use.
Handling steps:
1. Save the current Program Counter (PC) and registers.
2. Jump to the Interrupt Service Routine (ISR) whose address is placed in the PC.
3. Execute the ISR; if it involves data transfer, a buffer temporarily stores the data.
4. Restore saved registers and resume the interrupted task.
The transcript’s printer example (Figure 4.13) shows how a buffer lets the CPU continue other work while the printer processes the
page, preventing idle CPU time.
🔄 Multitasking
Multitasking allows several processes to share the CPU by rapidly switching contexts.
Administrator accounts can create, modify, or delete user accounts and set access rights.
Standard accounts have limited privileges, preventing accidental system changes.
This separation safeguards personal data and enforces security policies in multi‑user environments (e.g., universities,
enterprises).
During power‑on, the BIOS locates the storage device containing the OS and loads the necessary OS components into RAM.
CMOS chips hold the BIOS settings (e.g., clock speed, boot order); a small battery powers CMOS so settings persist after
shutdown.
Removing the battery resets the BIOS to factory defaults because the CMOS configuration is lost.
sum = a + b;
The intent is obvious without knowing any details of the underlying CPU.
Low‑Level Languages
Category Description When it’s useful
Machine code Binary instructions the processor executes Firmware, boot loaders,
directly (e.g., 0010 1101 0001 0100). performance‑critical kernels.
Assembly language Mnemonic representation of machine Writing device drivers, exploiting special
code (e.g., LDA FIRST). Each instruction hardware features, writing very tight
maps one‑to‑one to a binary opcode. loops.
Machine‑code snippet (adds two numbers, shown in hex and binary):
Note: Most IDEs integrate a translator of the appropriate type for the selected language (e.g., a Java compiler for a Java project, an
interpreter for a Python script).
Visualising Translation
The image below shows a user typing a prompt, which is then turned into binary before the computer can act on it.
The speech bubble “Please enter your name” is converted into a circular buffer of 0 s and 1 s—illustrating the role of a translator
(compiler or interpreter) that turns human‑readable text into machine‑readable binary.
Interrupt register – a special CPU register whose bits indicate pending interrupt requests.
Typical sequence:
1. Fetch – CPU fetches the next instruction.
2. Decode – Instruction is decoded; before execution the interrupt register is examined.
3. If a bit is set → CPU saves the current state (program counter, registers) on the stack.
4. Jump to the interrupt‑handler routine (a fixed address defined by the hardware).
5. Handler executes, clears the interrupt flag, and restores the saved state.
6. Resume the original instruction stream (back to the fetch stage).
This mechanism enables multitasking, I/O handling, and rapid response to hardware faults without constantly polling devices.
📚 Summary Tables
1. High‑Level vs Low‑Level Language Characteristics
Aspect High‑Level Low‑Level
Abstraction Close to natural language; hides hardware Directly maps to processor instructions
details
Portability Source runs on many architectures Tied to a single CPU family
(requires recompilation)
Typical size of source Concise, expressive Verbose (one line per machine instruction)
Learning curve Gentle (easier for beginners) Steep (requires hardware knowledge)
Use case Application software, rapid development Firmware, device drivers,
performance‑critical loops
2. Translator Comparison
Translator Translation Unit Execution Model When to prefer
Compiler Whole program Executes pre‑generated native Large, performance‑sensitive
code applications
Interpreter Single statement Executes on the fly Scripting, teaching, quick
prototyping
Assembler Assembly source Generates exact machine code Low‑level hardware work, boot
code
These notes extend the earlier sections on number systems, binary arithmetic and data representation by showing how binary data is
actually produced from human‑level programs, how that code is transformed into machine instructions, and how modern development
tools and CPU interrupt mechanisms support the whole software life‑cycle.
🔹 Session Cookies
Lifetime – exist only while the browser window (or tab) remains open; deleted automatically when the session ends.
Content – typically hold a temporary shopping‑basket identifier or a session‑ID; they do not contain personally identifying
information.
Use case – keep track of items added to an online cart (e.g., Wncn example) without persisting after logout.
⛓️ Blockchain Fundamentals
Blockchain – a decentralised database where each block contains a set of transactions and links to the previous block via a
cryptographic hash.
🧩 Block Structure
The 3‑D cube illustrates the three core components of a blockchain block: the Data section (sender, recipient, amount), the Hash value
(unique identifier generated by a cryptographic algorithm), and the Previous hash value (link to the preceding block). This visual shows
how each block is cryptographically chained to its predecessor.
🔄 How a Blockchain Grows
1. New transaction is created (e.g., Alice sends 0.5 BTC to Bob).
2. The transaction is placed in a pending pool until enough pending data fills a block.
3. A miner assembles the block, computes the hash of the block’s contents, and includes the previous‑block hash.
4. Proof‑of‑work forces the miner to find a nonce that makes the block hash satisfy a difficulty target (e.g., leading zeros). This
typically takes about ten minutes for Bitcoin.
5. Once the proof‑of‑work is found, the block is broadcast to all network nodes.
6. Every node verifies the block (checks the hash, validates transactions, ensures the proof‑of‑work). If valid, the block is
appended to the local copy of the blockchain.
Tamper resistance – Changing any data inside a block alters its hash; because the next block stores the previous hash, the chain
breaks and all subsequent blocks become invalid. An attacker would need to redo the proof‑of‑work for the altered block and for
every following block faster than the rest of the network, which is computationally infeasible.
🛡️ Cybersecurity Threats
🔐 Brute‑Force Attacks
Brute‑force attack – systematic trial of every possible password combination until the correct one is found.
Typical workflow:
1. Try the most common passwords (e.g., 123456, password, qwerty).
2. If none match, use a word‑list containing millions of candidate strings.
3. Optionally generate permutations (adding numbers, symbols, case changes).
Mitigation: enforce strong password policies (minimum length, mixed character classes), implement account lockout after a
few failed attempts, and use multi‑factor authentication.
📡 Data Interception
Data interception – unauthorized capture of data as it travels over a wired or wireless network.
Impact: users cannot access email, websites, or online services; ISPs may exceed quota limits, causing service degradation.
Counter‑measures:
Deploy firewalls with rate‑limiting rules.
Use traffic‑filtering services (e.g., Cloudflare) that absorb excess traffic.
Apply email filters to block spam bursts.
🕵️ Hacking
Hacking – illegal or unauthorised access to a computer system.
Malicious hacking: performed without consent, often for theft, sabotage, or extortion.
Ethical hacking: companies hire “white‑hat” professionals to test security (penetration testing) and harden systems.
Prevention: firewalls, strong passwords, regular patching, intrusion‑detection systems, and security awareness training.
🦠 Malware Types
Malware Core behaviour Typical delivery vector Example impact
Viruses Replicate by attaching to host Email attachments, Corrupt files, slow system
files; need user to run infected compromised downloads
program
Worms Self‑replicate across networks Exploit vulnerable services, Rapid network congestion
without user action email spreads (e.g., ILOVEYOU)
Trojan horses Appear legitimate but execute Deceptive installers, fake Install spyware, backdoors
hidden malicious code anti‑virus pop‑ups
Spyware Monitors user activity Bundled with free software, Theft of credentials, privacy
(key‑logging, browsing habits) hidden in downloads breach
and reports to attacker
Adware Forces unwanted advertising Free‑ware installers Annoyance, potential
(pop‑ups, toolbar redirects) redirection to malicious sites
Ransomware Encrypts user files and Phishing emails, malicious Total data loss unless backups
demands payment for attachments exist
decryption key
Key takeaway – many malware families rely on social engineering to convince the user to execute the payload; technical controls
alone are insufficient without user awareness.
Indicators: generic greetings (“Dear Customer”), mismatched sender addresses, urgency (“Your account will be closed”),
missing HTTPS padlock.
Defences: user education, anti‑phishing browser extensions, verify URLs (look for https:// and the green lock), avoid clicking
unknown links.
Pharming – manipulation of DNS resolution so that a legitimate domain name resolves to a malicious IP address.
📋 Activities
1. Cookie Classification – Visit [Link] Identify the domain name, the file name, and the
protocol (HTTP/HTTPS). Then list at least three differences between session and persistent cookies, and describe three
real‑world cookies you have encountered.
2. Digital vs. Crypto – Write a short paragraph comparing digital currency (centralised) with cryptocurrency (decentralised).
Highlight the main security and privacy differences.
3. Blockchain Walk‑through – Sketch a simple blockchain of three blocks on paper. Label each block’s Data, Hash, and
Previous hash fields. Explain what happens if the data in the middle block is altered.
4. Brute‑Force Simulation – Using a password‑cracking list (e.g., the 10‑most‑common passwords), simulate a brute‑force
attack on a dummy account. Record how many attempts were needed before success and discuss how password complexity
would affect the outcome.
5. Malware Identification – For each malware type in the table above, provide one real‑world example (e.g., WannaCry for
ransomware) and a brief description of its impact.
6. Phishing Detection – Examine a recent phishing email (or a screenshot provided by the instructor). Highlight at least four red
flags that indicate it is fraudulent.
7. DDoS Mitigation Plan – Draft a one‑page response plan for a small business that experiences a DDoS attack on its public
website. Include firewall rules, traffic‑filtering services, and communication steps with the ISP.
These activities reinforce the concepts of cookies, digital money, blockchain security, and the broad spectrum of cyber threats
discussed above.
Typical scenario: a cyber‑criminal leaves a contaminated memory stick where a curious employee finds it, plugs it in, and
unwittingly installs malware.
Phishing lure: an email promising a prize (e.g., a car) asks for credit‑card details. The victim’s curiosity and trust in
“official‑sounding” language lead to credential theft.
The attacker’s workflow (illustrated in Figure 5.12 of the lecture) follows these stages:
1. Identify a target.
2. Gather personal details (via fake calls, compromised sites, etc.).
3. Deliver malicious payload (malware, fake websites).
4. Exploit the victim’s rushed decisions to obtain money or data.
🛡️ Anti‑Malware Tools
Anti‑malware software detects, blocks, and removes malicious programs.
Anti‑virus – scans for known virus signatures, monitors file behaviour, and quarantines infected files (see Chapter X for
deeper coverage).
Anti‑spyware – targets spyware using three main techniques:
1. Rule‑based detection – looks for characteristic spyware patterns.
2. File‑structure analysis – recognises suspicious directory layouts.
3. Behavioural monitoring – blocks key‑logging, webcam hijacking, and unauthorized encryption.
Anti‑spyware is often bundled with firewalls and generic malware suites.
Factors of authentication
Something you know – password, PIN.
Something you have – mobile phone, security token.
Something you are – biometric trait (fingerprint, retina).
👆 Biometrics
Biometrics use unique physiological or behavioural traits for identity verification.
Fingerprint scanning
Compares ridge/valley patterns against stored templates.
Benefits: highly unique, difficult to forge, no physical token to lose.
Drawbacks: costly installation, may fail if fingers are injured, privacy concerns.
Retina scanning
Infrared light maps the unique blood‑vessel pattern at the back of the eye.
Accuracy: roughly 1 in 10 million false‑match rate.
Drawbacks: expensive, requires the user to remain still for ~10‑15 seconds, perceived as intrusive.
Comparative overview
Technique Benefits Drawbacks
Fingerprint Unique, cheap hardware, easy enrolment Sensitive to skin condition, can be lifted
from surfaces
Retina Extremely high accuracy, hard to spoof Expensive, slow, intrusive experience
Voice Hands‑free, works over phone lines Affected by background noise, voice
changes
Facial Non‑contact, works in public spaces Susceptible to photos/video spoofing,
lighting issues
🔑 Two‑Step Verification
Two‑step verification (2SV) requires two independent authentication factors before granting access.
The image shows a fake PayPal notice riddled with spelling mistakes, a generic link, and a mismatched sender address—classic phishing
cues.
Common typo‑squatting patterns
Substituting l for 1 or 0 for O (e.g., [Link]).
Adding extra characters (konGouJ) to mimic legitimate domains.
🔥 Firewalls
A firewall controls inbound and outbound traffic between a private network and external networks (e.g., the Internet).
🌐 Proxy Servers
A proxy server sits between a client and the destination web server, forwarding requests on the client’s behalf.
Functions:
Content filtering – blocks access to prohibited sites.
Anonymisation – masks the client’s IP address from the target server.
Caching – stores copies of frequently accessed pages, reducing latency and bandwidth usage.
DoS mitigation – absorbs malicious traffic before it reaches the origin server.
Proxies can act as an additional layer of protection alongside firewalls.
🔒 Privacy Settings
Privacy settings let users control which personal data is shared with websites, apps, and third‑party services.
📋 Practice Activities
1. Identify weak vs. strong passwords – evaluate a given list and justify each classification.
2. Design an access‑level matrix for a hospital system (e.g., doctors, nurses, admin staff, cleaning crew).
3. Map the phishing workflow (Figure 5.12) onto a real‑world scenario you have encountered.
4. Compare biometric techniques using the benefit/drawback table; propose a suitable method for a high‑security research
lab.
5. Simulate a two‑step verification: draft the user experience for a banking app, including fallback mechanisms for lost
phones.
6. Create a firewall rule‑set that blocks all inbound traffic except HTTPS (port 443) and allows outbound DNS (port 53).
7. Analyse a suspicious email (phishing screenshot) and list every red flag present.
These activities reinforce the security concepts introduced in this section and prepare you for applied examinations.
Blockchain – a decentralised database in which every transaction is stored in a linked series of blocks. The network consists of
many interconnected computers (peers) rather than a single central server.
Timestamp – a digital record that records the exact date and time a data block is created in a blockchain.
Proof‑of‑Work – the algorithm that miners use to confirm transactions and create new blocks. It requires solving a computational
puzzle; the first miner to solve it adds the block and receives a reward.
The diagram below visualises a single blockchain block, showing how the data, hash, and previous‑hash fields are linked together.
Each block contains the transaction data, a unique hash generated from that data, and the hash of the preceding block. Changing
any data alters its hash, which breaks the chain and signals tampering.
🛡️ Cyber‑Attack Techniques
Brute‑Force Attack & Word List
Brute‑force attack – a method used by cyber‑criminals to crack passwords by trying every possible combination of letters,
numbers, and symbols until the correct one is found.
Word list – a plain‑text file that stores thousands of common words; attackers feed the list to a brute‑force program to speed up
guessing.
Data interception – an attempt to eavesdrop on a wired or wireless transmission; the attacker captures packets to read or modify
the data.
Packet sniffing – a technique where a cyber‑criminal examines data packets travelling over a network, extracting useful information
(e.g., usernames, passwords).
Wardriving – using a laptop, antenna, GPS, and software to locate and map Wi‑Fi access points, then intercepting the wireless
traffic (sometimes called access‑point mapping).
WEP (Wired Equivalent Privacy) – an early encryption protocol for Wi‑Fi networks; it is now considered weak because it can be
cracked with relatively simple tools.
DoS attack – a cyber‑attack that overwhelms a target (e.g., a web site or mailbox) with a flood of requests, rendering the service
unusable.
DDoS attack – a DoS attack launched from many compromised computers, making mitigation far more difficult.
Spam – unsolicited bulk email used to clutter users’ inboxes; often the front‑end of a DoS campaign against mail servers.
🐛 Malware Families
Malware type How it spreads / behaves Typical impact
Virus Attaches to an active host program; Deletes or corrupts files; may cause
replicates when the host is executed. system crashes.
Worm Stand‑alone; self‑replicates across Rapidly consumes bandwidth and can
networks without user interaction. deliver payloads.
Trojan horse Disguised as legitimate software but Opens back‑doors, steals data, or installs
contains hidden malicious code. additional malware.
Spyware Monitors user activity (keystrokes, web Privacy breach; can lead to identity theft.
browsing) and reports back to the
attacker.
Adware Forces unwanted advertisements onto the Annoyance, possible redirection to
user’s screen. malicious sites.
Ransomware Encrypts the victim’s files and demands a Data loss until ransom is paid (or backup
payment for the decryption key. is restored).
Spear phishing – a targeted form of phishing aimed at specific individuals or organisations; the content is customised to increase
credibility.
Pharming – redirecting a user’s browser to a fraudulent website without any action from the user, typically by corrupting DNS
information.
DNS cache poisoning – altering the IP address stored in a DNS server’s cache so that a legitimate domain resolves to a malicious
site.
The screenshot illustrates a classic phishing email: poor spelling, a generic greeting, and a mismatched sender address.
Notice the spelling errors (“your account will be clsed”), the generic “Dear Customer”, and the link that points to a domain different
from the official PayPal address.
Biometrics – authentication that uses a unique human characteristic (e.g., fingerprint, voice, retina blood‑vessel pattern).
Two‑step verification – requires two independent verification methods (e.g., password + one‑time code) to prove identity.
Access Levels
Access levels – hierarchical permissions that determine which resources a user can view or modify (e.g., Administrator > Standard
user > Guest).
Anti‑spyware – software that detects and removes spyware based on known signatures or behavioural rules.
Patch – a software update that fixes bugs or security vulnerabilities; applying patches promptly reduces the attack surface.
Typo‑Squatting
Typo‑squatting – registering domain names that contain subtle spelling errors (e.g., [Link]) to trick users into visiting
malicious sites.
🔥 Network Defences
Firewall
Firewall – hardware or software placed between a computer (or internal network) and an external network; it monitors and filters all
incoming and outgoing traffic according to a set of rules.
Proxy Server
Proxy server – an intermediary that forwards client requests to the Internet; it often caches content to speed up repeated accesses
and can enforce additional security policies.
Privacy Settings
Privacy settings – controls provided by social‑networking sites and browsers that let users limit who can see their profile or what
data is collected (e.g., disabling third‑party cookies).
SSL/TLS – a security protocol that encrypts data transmitted between a web browser and a server, preventing eavesdropping and
tampering.
SSL certificate – a digital certificate issued by a trusted Certificate Authority; it authenticates the website’s identity and enables the
encrypted SSL/TLS connection.
When a site presents a padlock icon and an “[Link] URL, the SSL certificate has been verified and the communication channel is
encrypted.
These notes expand on the cybersecurity terminology introduced earlier (cryptography, binary concepts, etc.) and integrate the new
material into a single, continuous study guide.
Key point – The system reduces energy consumption because illumination occurs only when needed, and wireless links avoid
extensive cabling.
Advantage Disadvantage
Adjustable brightness & colour via programmable microcontroller Higher initial cost, especially for wireless components
Energy savings (lights on only when required) Wireless links can be less reliable than wired ones
Longer bulb life due to dimming and controlled switching More maintenance may be needed over time
Key point – Automation yields consistent, repeatable results and speeds up research, but it is less flexible than manual operation.
Advantage Disadvantage
Consistent, repeatable results; reduced hazardous exposure Less flexibility; skilled staff still needed for setup
Faster turnaround; parallel experiments possible High upfront equipment cost
Automatic data analysis; results can be accessed remotely Security risks when data are shared over networks
Fewer highly trained operators required per experiment Maintenance and calibration of sensors can be expensive
🧠 What Is Robotics?
Robotics – the interdisciplinary field that combines computer science, engineering, and electronics to design, construct, and operate
robots.
The term robot derives from the Czech robota (“forced labour”), first used in the 1920 s play R.U.R. (Rossum’s Universal
Robots).
Isaac Asimov’s Three Laws (fictional but influential):
1. A robot may not injure a human or allow a human to come to harm through inaction.
2. A robot must obey orders given by humans, unless those orders conflict with the First Law.
3. A robot must protect its own existence, as long as such protection does not conflict with the First or Second Law.
Robots appear in many domains:
Industrial – welding, painting, assembly, warehouse logistics.
Transport – autonomous cars, driverless trains, drones.
Agriculture – harvesting robots, weed‑removal units, phenotyping scanners.
Medical – surgical assistants, patient‑monitoring bots, prosthetic limbs.
Domestic – autonomous vacuum cleaners, personal‑assistant robots.
Entertainment – theme‑park animatronics, camera‑control rigs, stunt‑performing humanoids.
Note – Not all “robots” possess artificial intelligence; many simply repeat programmed motions without adaptive decision‑making.
🏭 Industrial Robotics
Programming approaches
1. Teach‑pendant / manual teaching – an operator moves the robot arm; each position is recorded as an instruction.
2. Offline programming – a human writes a sequence of commands on a computer; the robot later executes them identically.
🚗 Autonomous Vehicles
Common architecture (applies to cars, trains, and aircraft)
Sensors – radar, ultrasonic rangefinders, cameras, LiDAR build a 3‑D model of surroundings.
Microprocessor – fuses sensor data, runs decision algorithms, and issues commands.
Actuators – control steering, throttle, brakes, doors, or flight surfaces.
🌾 Agricultural Robotics
Application How it works Advantages Disadvantages
Harvesting/picking Vision systems detect ripe Faster, higher yields; less waste High upfront cost; may struggle
fruit; robotic arms cut and with irregular crop shapes
collect without damage
Weed control AI distinguishes weeds from Saves labour; reduces Requires reliable GPS signal;
crops; actuated blades remove herbicide use maintenance of cutting tools
weeds along GPS‑guided rows
Phenotyping Multi‑spectral cameras create Rapid disease detection; Large data volumes demand
3‑D models of plants; precise growth tracking strong processing power
machine‑learning analyses
health indicators
Seed‑planting & fertiliser Aerial robots spray seeds or Uniform coverage; reduced Weather dependence; battery
drones nutrients with GPS accuracy; chemical runoff life limits operation time
some also perform
cloud‑seeding
All these devices are autonomous: they can pause when weather turns bad and resume when conditions improve.
🏥 Medical Robotics
Surgical assistants – robots hold instruments steady, improving precision and reducing operation time.
Patient monitoring – autonomous systems draw blood samples, locate veins, and alert staff to infections.
Targeted therapy – micro‑robots deliver drugs to specific tissue sites, minimising side effects.
Prosthetics & bionic skins – embedded sensors and actuators provide feedback, allowing users to control artificial limbs
naturally.
Benefit – Enhanced safety, faster procedures, and the ability to perform tasks in sterile or hazardous environments.
Challenge – High equipment cost and the need for rigorous validation to avoid malfunctions during critical procedures.
Disadvantages
Shifts required skill sets; humans may become overseers rather than operators.
AI performance depends heavily on the quality and breadth of its training data.
Ethical concerns about decision‑making authority and potential bias.
📋 Activity Summaries
6.7 – Match sensors to a train, a vaccine‑mixing line, and an art‑gallery lighting system; evaluate pros/cons of automation.
6.8 – Create a table of advantages and disadvantages for agricultural robots.
6.9 – For five agricultural robot examples, list efficiency gains and labour reductions, then note drawbacks.
6.10 – Research three live entertainment robots; outline their benefits and limitations.
6.11 – Provide four advantages and four disadvantages of using robots in manufacturing.
6.12 – Complete sentences using a word list describing autonomous cars, sensor types, and control flow.
6.13 – Describe how underwater and space‑exploration robots use sensors, cameras, actuators, and microprocessors; list
two further autonomous‑robot use cases.
These activities reinforce the concepts of sensing, actuation, programming, and the trade‑offs inherent in deploying automated and
robotic systems across diverse sectors.
AI Categories
Category Performance compared with a human Typical scope
Narrow AI Performs one specific task at or above Speech‑to‑text, image classification
human level
General AI Performs a specific task at roughly human A robot that can navigate a home and
level answer questions
Strong AI Superior to humans across many tasks Hypothetical super‑intelligent system
Deductive reasoning – building a set of correct facts, forming rules from them, then applying those rules to new problems.
Example: an AI that learns how to brew the perfect cup of tea can, after observing the process, apply the same principles to
make coffee, hot chocolate, etc., tweaking the methodology each time.
By executing a sequence of steps, the AI refines its internal model, enabling it to handle novel situations more effectively.
Pattern recognition – AI can detect regularities in data far faster than humans, then use those patterns to make predictions on fresh
inputs.
🗣️ AI‑Powered Applications
Application How AI works Example
News generation Ingests live feeds, extracts key facts, Automated sports recap articles
assembles readable paragraphs
Smart‑home assistants (Alexa, Speech‑recognition → natural‑language Adjusting thermostat based on daily
Google Now, Siri, Cortana) processing → action execution; learns user routines
habits over time
Chatbots Text‑based dialogue; match user input to Customer‑service bot answering order
a knowledge base; generate appropriate status
reply
Facial‑expression recognition Detects landmarks (eyebrow corners, Emotion‑aware advertising displays
mouth corners); maps combinations to
emotions (anger, joy, surprise)
🧠 Expert Systems
Expert system – a computer program that mimics the decision‑making ability of a human specialist by using a knowledge base and
an inference engine.
Core Components
Component Role
User interface Presents questions (often Yes/No) and receives answers from
the user.
Inference engine Acts as a search engine; matches user responses against the
knowledge base using inference rules.
Knowledge base Repository of facts – objects and their attributes (e.g., whale:
mammal = yes, lives in water = yes).
Rules base Collection of IF‑THEN statements that drive the reasoning
process (e.g., IF habitat = water AND legs = 0 THEN animal =
whale).
Typical Workflow
1. User answers a series of guided questions.
2. The inference engine applies the rules base to the collected answers.
3. A conclusion is drawn, accompanied by a probability indicating confidence (e.g., “21 % chance of oil‑bearing rocks”).
4. The explanation system (a sub‑module) tells the user why that conclusion was reached.
Advantages & Disadvantages
Advantages Disadvantages
High expertise & consistent results Requires extensive training of users to operate correctly
Fast response time; can store vast amounts of knowledge “Cold” responses may be inappropriate in some contexts
Provides traceable reasoning & probability of correctness Assumes infallibility of entered data; may propagate errors
Learning Process
1. Data collection – gather labelled examples (e.g., spam vs. non‑spam emails).
2. Training – the algorithm adjusts internal parameters to minimise prediction error.
3. Evaluation – test the trained model on a separate dataset to gauge accuracy.
4. Deployment – the model is used to classify new inputs in real time.
Representative Examples
Example Input features Output
Spam filtering Email header, body keywords, sender Spam / Not spam
address
Recommendation engines (collaborative Purchase histories of many customers Suggested products for a new user
filtering)
Fraud detection Transaction amount, location, time, device Legitimate / Fraudulent
ID
Search‑engine ranking Query terms, click‑through data, page Ordered list of webpages
relevance signals
Comparison with Expert Systems
Aspect Expert System Machine Learning
Knowledge acquisition Manual encoding of expert rules Automatic learning from data
Flexibility Limited to predefined rules Adapts to new patterns
Explainability Transparent (IF‑THEN) Often a “black box” (especially deep
models)
Maintenance Updating rules can be labor‑intensive Retraining with fresh data updates
performance
Architecture Overview
1. Input layer – receives raw data (e.g., pixel RGB values).
2. Hidden layers – each layer transforms its input using weighted connections and non‑linear activation functions; deeper
networks can capture abstract features.
3. Output layer – produces the final prediction (e.g., object class).
Artificial neural network (ANN) – a set of nodes (artificial neurons) loosely modeled on the human brain’s interconnections.
📊 Comparative Summary
Feature Expert System Machine Learning Deep Learning
Knowledge source Human experts (explicit) Historical data (implicit) Large labeled datasets
Reasoning style Rule‑based, symbolic Statistical inference Hierarchical representation
Transparency High (IF‑THEN) Moderate (model coefficients) Low (many hidden weights)
Typical domains Medical diagnosis, mineral Spam detection, Image/video analysis, speech
prospecting recommendation, fraud recognition
Training effort Manual rule authoring Feature engineering + model Massive compute + data
tuning preprocessing
As discussed earlier, the analysis stage clarifies what the program must achieve, while design focuses on how the tasks will be
organised.
Top‑down design starts with a high‑level description of the whole system and repeatedly breaks each component into finer
details.
Each sub‑system can be documented with a structure diagram that shows the hierarchy of modules.
This hierarchical breakdown lets several programmers develop different modules concurrently, reducing overall development time.
The flowchart starts by initialising PassCount ← 0, loops over each student, increments the counter when the mark exceeds 50, and
finally outputs the total passes.
The variable on the left receives the value of the expression on the right.
Conditional statement (IF … THEN … ELSE)
CASE Day OF
1: Output "Monday"
2: Output "Tuesday"
…
OTHERWISE: Output "Invalid day"
ENDCASE
Loop structures
Loop type Syntax example When to use
FOR … NEXT FOR i ← 1 TO 10 Fixed number of repetitions
Sum ← Sum + i
NEXT i
REPEAT … UNTIL REPEAT Execute at least once, stop when a
Input Mark condition becomes true
IF Mark > 50 THEN PassCount ←
PassCount + 1
UNTIL Mark = -1
WHILE … ENDWHILE WHILE NotEnd Unknown number of repetitions; test
ProcessItem() condition before each iteration
ENDWHILE
Input / Output
INPUT Variable reads a value from the user.
OUTPUT Text, Variable displays text (and optionally a variable) on the screen.
7.4.2 Counting
Counting pattern: initialise a counter, increment each time a condition is met. The flowchart above illustrates this technique.
Found ← FALSE
FOR i ← 1 TO ListSize
IF List[i] = Target THEN
Position ← i
Found ← TRUE
EXIT FOR
ENDIF
NEXT i
The algorithm scans each element until the target is located (or the list ends).
REPEAT
Swapped ← FALSE
FOR i ← 1 TO n‑1
IF List[i] > List[i+1] THEN
TEMP ← List[i]
List[i] ← List[i+1]
List[i+1] ← TEMP
Swapped ← TRUE
ENDIF
NEXT i
UNTIL NOT Swapped
Repeatedly swaps adjacent out‑of‑order items; the process stops when a complete pass makes no swaps.
Validation in a user‑interface
The pop‑up window shown below demonstrates required fields (asterisk) that would be validated before allowing submission.
The form marks Email, Confirm Email, Password and Confirm Password as required; typical validation would check that the two email
fields match, that the password meets length/complexity rules, and that no field is left empty.
Example validation pseudocode (percentage mark)
REPEAT
INPUT Mark
IF Mark < 0 OR Mark > 100 THEN
OUTPUT "Invalid mark – enter a value between 0 and 100"
ENDIF
UNTIL Mark >= 0 AND Mark <= 100
The loop repeats until a value satisfying the range and type checks is entered.
Normal test data represent typical, valid inputs the program will encounter in everyday use.
Edge‑case data explore the limits of the specification (e.g., minimum/maximum values, empty inputs).
These notes extend the earlier coverage of number representation, binary arithmetic and data storage by detailing how to design,
document, implement, validate, and test algorithms—essential skills for constructing reliable computer programs.
Using test data 7.3, 12, 40, 150, 300, 110, 60, 150, 130 the completed trace table (Table 7.4) records the evolution of A, B , C and the
final output of the largest and smallest numbers.
Activity 7.12 – Build a trace table for the above flowchart using the test data set listed above.
Activity 7.13 – Apply the same trace‑table technique to the pseudocode version of the max/min algorithm (provided later) with test
data 19, 17.3, 14, 8, ....
Activity 7.14 – Dry‑run the bubble‑sort algorithm (page 276) with the data 35, 31, 32, 36, 35, 37, 42, 38 and complete a trace table
showing each pass.
Standard stages
1. Specification – Clearly state the problem purpose and required tasks.
2. Decomposition – Break the problem into smaller sub‑problems (e.g., input, processing, output).
3. Structure diagram – Hierarchical visual that shows the relationship between sub‑systems.
4. Flowchart or pseudocode – Choose a representation that best communicates the logic.
5. Validation & verification – Apply normal, abnormal, extreme, and boundary test data; record results in trace tables.
6. Iterative refinement – Correct any errors uncovered, repeat testing until the algorithm is reliable.
Example: Ticket‑discount algorithm (pseudocode)
REPEAT
INPUT tickets
IF tickets = 0 THEN EXIT REPEAT
IF tickets <= 10 THEN
discount ← 0
ELSEIF tickets <= 20 THEN
discount ← 0.10
ELSE
discount ← 0.20
ENDIF
total ← tickets * price_per_ticket * (1 - discount)
OUTPUT total
ENDREPEAT
Activity 7.18 – Identify the test‑data type for each of the following inputs and perform a dry‑run: 20, 400, 1920, 342, 320.
Activity 7.19 – Modify the algorithm to handle 12 diners and a bill range of £10 – £500; list the validation checks required for “number
of diners” and “bill size”.
Activity 7.20 – Write pseudocode that repeatedly prompts the user for positive numbers, stops when a non‑positive value is entered,
then outputs the total and average. Explain why a repeat‑until loop is appropriate.
Boundary data – Values that lie exactly on the edge of the valid range; one side is accepted, the other rejected.
Dry‑run – Manual execution of an algorithm using test data, often recorded in a trace table.
Extreme data – The smallest or largest permissible values within the valid range.
Trace table – Tabular record of variable values after each step of a dry‑run.
Validation – Automated checks that confirm data are sensible before use.
Top‑down design – Starting with a high‑level description and iteratively refining into detailed steps.
Flowchart – Diagrammatic representation of algorithmic flow, showing processes, decisions, and loops.
Algorithmic error – Logical flaw that causes incorrect output for some test data.
Test data categories – Normal, abnormal, extreme, and boundary data used to fully exercise an algorithm.
These notes build on earlier sections about number systems, binary arithmetic, and data representation, now focusing on algorithm
validation, trace‑table techniques, and systematic design—essential skills for constructing reliable programs and for succeeding in
IGCSE Computer Science examinations.
📐 Programming Fundamentals
🔢 Sequence & Algorithm Steps
Sequence – the ordered execution of statements in an algorithm.
If the steps are placed in the wrong order the program can produce incorrect results or perform unnecessary work, as highlighted
earlier in the total‑average example.
🔀 Selection Statements
📊 IF‑THEN‑ELSE
IF evaluates a condition; if TRUE the following block runs, otherwise the ELSE block runs.
Pseudocode pattern
IF condition THEN
statements‑if‑true
ELSE
statements‑if‑false
ENDIF
Structure
CASE variable OF
value1 : statements‑1
value2 : statements‑2
…
OTHERWISE : default‑statements
ENDCASE
Typical use – menu selection, grading scales, or handling different command‑line options.
🔁 Iteration Structures
Loop type When to use Key characteristic
FOR (count‑controlled) Known number of repetitions Initialise, test, increment in one line
WHILE (pre‑condition) Unknown repetitions, condition must be May execute zero times
true before each iteration
REPEAT…UNTIL (post‑condition) Must execute at least once, stop when Test after the loop body
condition becomes true
The diagram demonstrates the loop structure, the placement of the counter initialisation, and the post‑loop average calculation.
Key points
Totalling – add each entered mark to a running total.
Counting – increment a counter each time a valid mark is entered.
Average – compute average = total / count after the loop, ensuring the sentinel value is excluded.
🧵 String Handling
Operation Description Example (pseudocode)
Length Returns the number of characters in a len ← LENGTH("Computer Science") // len
string. = 16
Substring Extracts a portion of a string given a start sub ← SUBSTRING("Computer Science", 9,
index and length. 7) // sub = "Science"
Uppercase Converts all alphabetic characters to up ← UPPER("Computer Science") // up =
upper case. "COMPUTER SCIENCE"
Lowercase Converts all alphabetic characters to lower low ← LOWER("Computer Science") // low
case. = "computer science"
Strings are indexed from 0 in most languages (e.g., Python, Java) but from 1 in Visual Basic. Adjust your start position accordingly.
Boolean Operators
Symbol Meaning
AND Both operands true
OR Either operand true
NOT Negates the operand
These operators can be combined, e.g., IF (score >= 50) AND (attempts < 3) THEN ….
🔄 Nested Statements
Nested structures place one control statement inside another, reducing code duplication.
Example – nested loops for marks per subject
REPEAT
INPUT mark
IF mark = 999 THEN EXIT REPEAT
IF mark >= 50 THEN
PASSCOUNT ← PASSCOUNT + 1
ELSE
FAILCOUNT ← FAILCOUNT + 1
ENDIF
UNTIL FALSE
Procedure – a named block of statements that performs a task but does not return a value.
Function – similar to a procedure but returns a single value to the caller.
Both may accept parameters (input values). In IGCSE Computer Science a maximum of two parameters is typical.
PROCEDURE DisplayStars
FOR i ← 1 TO 3 DO
OUTPUT "* * *"
NEXT
ENDPROCEDURE
CALL DisplayStars
PROCEDURE PrintStars(count)
FOR i ← 1 TO count DO
OUTPUT "*"
NEXT
ENDPROCEDURE
c ← ToCelsius(68) // c = 20
In Java the keyword return ends a function; in Python the def block uses return.
📚 Library Routines
Routine Purpose Example (pseudocode)
DIV(a, b) Integer division – returns the quotient q ← DIV(27, 5) // q = 5
MOD(a, b) Modulus – returns the remainder r ← MOD(27, 5) // r = 2
ROUND(x, n) Rounds x to n decimal places y ← ROUND(3.14159, 2) // y = 3.14
RANDOM(min, max) Returns a random integer between min r ← RANDOM(1, 100)
and max (inclusive)
These routines are part of the standard library in most IGCSE languages (e.g., [Link] in Java, [Link] in Python).
📚 Arrays
Declaration
The first index is typically 0 (Python, Java, C) unless the language specifies otherwise (Visual Basic starts at 0 as well).
FOR i ← 0 TO 9 DO
INPUT scores[i]
NEXT
Accessing elements
Read: value ← scores[3] (fourth element)
Write: scores[7] ← 85
Arrays enable compact storage, easy searching, and bulk operations such as calculating class averages.
When the first index is 0 the element is at the top‑most row; the second index 0 points to the left‑most column.
The figure shows a three‑column, ten‑row table called MyTable. The first column is labelled “First element”, the last column “Last
element”. The blue boxes highlight the first and last elements of the table (positions 0,0 and 9,2).
Declaring a 2‑D array in pseudocode
The comments (//) in the pseudocode describe each stage: open, write/read, close.
Language‑specific snippets
Python
# write a line
with open("[Link]", "w") as f:
[Link]("Please enter a line of text\n")
Visual Basic
Java
import [Link].*;
Why databases?
Consistency – a change is made once, instantly visible to all users.
No duplication – the same piece of data is stored only one time.
Core concepts
Concept Definition
Field A column in a table; stores one attribute of each record (e.g.,
FirstName).
Record A row in a table; contains all field values for a single entity (e.g.,
one patient).
Primary key A field (or combination) whose values are unique for every
record; used to identify a record unambiguously.
Validation Automatic checks that ensure entered data meet required
formats (e.g., dates, numeric ranges).
Data type Specifies the kind of value a field can hold: Text, Number,
Date/Time, Boolean.
Core clauses (the only mandatory ones are SELECT and FROM)
Clause Purpose Syntax example
SELECT List the fields to be displayed SELECT FirstName, FamilyName
FROM Identify the table source FROM PATIENT
WHERE Filter rows by a condition WHERE Consultant = 'Mr Smith'
ORDER BY Sort the result set ORDER BY FamilyName ASC
COUNT Count rows (or non‑null values) SELECT COUNT(*) FROM PATIENT
SUM Add numeric values together SELECT SUM(Badges) FROM CUB
Example queries
1. Patients of a particular consultant
SELECT COUNT(*)
FROM PATIENT
WHERE DateOfAdmission BETWEEN #2022-10-01# AND #2022-10-31#;
4. Sum of badges earned by cubs in the “red” six (assuming a field Six holds the colour)
SELECT SUM(Badges)
FROM CUB
WHERE Six = 'red';
📋 Database‑Related Activities
Activity Task
9.1 List the fields you would expect for a DoctorAppointments table;
give each a suitable name (no spaces).
9.3 Choose appropriate data types for the PATIENT fields listed
above; include validation checks for WardNumber and
BedNumber.
9.5 Write an SQL query to list all patients whose admission date is
12/11/2022.
9.6 Write an SQL query that counts the number of patients in each
ward; display the ward number and the count.
9.7 Build the CubScout database (see Figure 9.8). Create fields:
CubNumber, CubName, DateOfBirth, Gender, School, Address,
Six (colour group), Badges. Add validation rules (e.g., Gender
limited to Male/Female/Other).
9.8 For a Students table, decide which field should be the primary
key, select data types, and define validation rules (e.g., email
format, date of birth). Populate with at least 10 records spanning
three classes, then write SQL scripts to:
• List students alphabetically by family name.
• Show each class’s students grouped together.
• Count how many students are in each grade.
DML (Data Manipulation Language) – SQL commands that insert, update, delete, or retrieve data (e.g., INSERT, UPDATE,
SELECT).
In A‑Level studies, multiple related tables are linked via foreign keys, and joins are used to combine data from those tables. The
fundamentals covered here—single‑table design, primary keys, validation, and basic SELECT statements—form the foundation for those
more advanced topics.
The script shows the full DDL cycle: create a database, define a table with appropriate data types, then enforce a primary key to
guarantee each cub record is unique.
Guarantees referential integrity when other tables reference this table (later topics on relational joins).
Must be immutable – its value should never change after insertion.
Common choices: auto‑increment integer IDs, national identification numbers, or a composite of several fields when no
single field is unique.
2. CYCLE inventory – For each field (ModelNo, Description, WheelSize, Price, InStock, etc.) specify a suitable SQL data type,
the required validation (e.g., Price > 0, WheelSize limited to standard sizes), and identify the primary key (ModelNo).
3. PERFORMANCE schedule – Count the fields and records in the provided performance table; propose two validation checks
for the ShowNumber field (e.g., “must be a 5‑digit integer” and “must be unique across the season”).
These items reinforce the single‑table design workflow: requirements → data‑type selection → primary‑key selection → DDL → DML
queries.
The top half describes the NOT gate (output is the inverse of the single input). The bottom half details the AND gate (output is true
only when both inputs are true).
These symbols map directly to Boolean algebra expressions used throughout the chapter, a continuation of the earlier discussion on
binary arithmetic.
and
X = (¬A ∧ B) ∨ (A ∧ ¬B)
represent the same logic function—both are algebraic rearrangements of the XOR truth table.
Half‑Adder
Input Output (Sum) Output (Carry)
,
A = 0 B = 0 0 0
,
A = 0 B = 1 1 0
,
A = 1 B = 0 1 0
,
A = 1 B = 1 0 1
Implemented with one XOR gate (producing the Sum) and one AND gate (producing the Carry).
Full‑Adder
A B Cin
Sum (S) Carry‑out (C )
out
0 0 0 0 0
0 0 1 1 0
0 1 0 1 0
0 1 1 0 1
1 0 0 1 0
1 0 1 0 1
1 1 0 0 1
1 1 1 1 1
The full‑adder circuit consists of two half‑adders and an OR gate to combine the two carry outputs. The diagram in Figure 10.41
(below) visualises this arrangement.
The left half‑adder processes A and B ; its Sum feeds into the second half‑adder together with C . The two Carry outputs feed an
in
OR gate, yielding C .
out
These adder circuits underpin binary arithmetic in CPUs—a direct link back to the earlier sections on binary addition and overflow.
📋 Consolidated Activities
Activity Core Skill
10.1 – Show equivalence of two XOR‑style expressions Boolean algebra manipulation
10.2 – Produce truth tables from given circuits Systematic truth‑table generation
(Figures 10.12, 10.15)
10.3 – Translate a truth table into a logic expression and circuit Reverse engineering of Boolean functions
10.4 – Design a safety‑system circuit for a wind‑turbine (three Real‑world application of AND/OR/NOT combinations
sensor inputs) and complete its truth table
Half‑adder / Full‑adder – Build the circuits, verify with truth Connecting arithmetic to logic‑gate design
tables
These exercises cement the transition from abstract Boolean expressions to tangible hardware implementations, a theme that runs
through the entire chapter series.
AND A∧B A ∧ B
OR A∨B A ∨ B
These symbols were introduced earlier; you should recognise them when constructing truth tables or drawing circuits.
Alarm condition – The output Y (motor & pump shut‑off) is true if any of the following combos occur:
1. M = 1 and T = 1 (speed 2000 rpm & temperature 90 °C)
2. M = 1 and V = 1 (speed 2000 rpm & velocity 1 m/s)
3. T = 1 and V = 1 (temperature 90 °C & velocity 1 m/s)
Boolean expression
Y = (M ∧ T ); ∨; (M ∧ V ); ∨; (T ∧ V )
Truth table
M T V M ∧ T M ∧ V T ∧ V Y
0 0 0 0 0 0 0
0 0 1 0 0 0 0
0 1 0 0 0 0 0
0 1 1 0 0 1 1
1 0 0 0 0 0 0
1 0 1 0 1 0 1
1 1 0 1 0 0 1
1 1 1 1 1 1 1
Logic circuit – Two‑input AND gates generate the three pairwise products; a three‑input OR gate (or two cascaded ORs) combines
them to form Y .
If the temperature sensor provides two thresholds (150 °C and 200 °C), treat the 200 °C condition as a separate input T 200 .
X = T200 ∧ (P ∨ S )
P S T200 P ∨ S X
0 0 0 0 0
0 1 1 1 1
1 0 1 1 1
1 1 1 1 1
… … … … 0 (when T 200 = 0 )
Two‑input gate implementation
OR gate for P and S (both have at most two inputs).
AND gate combines the OR output with T . 200
Half‑adder – circuit that adds two binary bits (A, B) producing a sum and a carry‑out, but without a carry‑in.
Truth table – tabular representation of all possible input combinations and the resulting output of a Boolean function.
Boolean expression – algebraic formula using logical operators (¬, ∧, ∨, ⊕) that describes a digital logic function.
Logic gate – basic electronic building block that performs a single Boolean operation (e.g., AND, OR, NOT).
Sensor – device that converts a physical quantity (speed, temperature, pressure) into a binary signal for use in a logic circuit.
Alarm / safety output – the final binary result of a circuit that triggers an external action (e.g., motor shut‑off, audible alarm).
Two‑input restriction – design rule requiring each gate to have no more than two inputs; achieved by cascading gates when more
inputs are needed.
These definitions build on earlier sections covering binary arithmetic, logic gate symbols, and circuit design.