0% found this document useful (0 votes)
139 views97 pages

Logic Gates and Number Systems Guide

This document provides an overview of logic gates, digital circuits, and data representation, including number systems such as binary, decimal, and hexadecimal. It explains conversion methods between these systems, binary arithmetic, and character encoding standards like ASCII and Unicode. Key concepts include the design of circuits, binary addition, overflow in registers, and the use of two's complement for signed integers.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
139 views97 pages

Logic Gates and Number Systems Guide

This document provides an overview of logic gates, digital circuits, and data representation, including number systems such as binary, decimal, and hexadecimal. It explains conversion methods between these systems, binary arithmetic, and character encoding standards like ASCII and Unicode. Key concepts include the design of circuits, binary addition, overflow in registers, and the use of two's complement for signed integers.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

📚 Logic Gate Design

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

📊 Data Representation Overview


Data representation is how computers store and manipulate information such as numbers, text, sound, and images using binary data.

🔢 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.

3️⃣ Hexadecimal (base‑16)


Hexadecimal (often shortened to hex) uses sixteen symbols: 0‑9 and A‑F (where A = 10, …, F = 15).

One hex digit represents exactly four binary bits.


Example: the hex digit 9 = binary 1001; C = binary 1100.
Hex digit Decimal value 4‑bit binary
0 0 0000
1 1 0001
… … …
A 10 1010
B 11 1011
C 12 1100
D 13 1101
E 14 1110
F 15 1111
🔄 Converting Between Number Systems
↔️ Binary ↔ Decimal
Method 1 – Subtract Powers of 2
1. List the powers of 2 from left to right (… 64 32 16 8 4 2 1).
2. Starting with the highest power ≤ the target number, subtract it and write 1; otherwise write 0.
3. Continue until the value reaches 0.
Example (binary 110 1110 → decimal):
Powers: 64 + 32 + 8 + 4 + 2 + 1 → sum = 111 (illustrative; exact total given in transcript).
Method 2 – Repeated Division by 2
1. Divide the decimal number by 2.
2. Record the remainder (0 or 1).
3. Use the quotient for the next division.
4. Continue until the quotient is 0.
5. Read the remainders bottom‑to‑top to obtain the binary result.
Example (decimal 142 → binary):
Division step Quotient Remainder
142 ÷ 2 71 0
71 ÷ 2 35 1
35 ÷ 2 17 1
17 ÷ 2 8 1
8 ÷2 4 0
4 ÷2 2 0
2 ÷2 1 0
1 ÷2 0 1
Binary result (reading remainders upward): 10001110 (8‑bit).
Activity 1.1 – Binary → Decimal
Convert the following binary numbers to decimal:
0
00
1
1110
01
1
(Students should apply either method above.)
Activity 1.2 – Decimal → Binary (both methods)
Convert each decimal number to binary using both subtraction‑of‑powers and division methods:
Decimal Binary (method 1) Binary (method 2)
2 10 10
5 101 101
5 101 101
4 100 100
0 0 0
9 1001 1001
56 111000 111000
33 100001 100001
0D0 – (hex digit) – –
8 1000 1000
8 1000 1000
€ 6 23 0 7 – (non‑numeric) – –
(Only the numeric rows are required for exam practice.)

↔️ 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

2. Multiply each hex digit by its positional value.


3. Sum the results.
Example (hex 45A → decimal):
2 1 0
4!×!16 ; +; 5!×!16 ; +; A!×!16 = 4!×!256; +; 5!×!16; +; 10!×!1 = 1024; +; 80; +; 10 = 1114

Decimal → Hexadecimal (successive division by 16)


1. Divide the decimal number by 16.
2. Record the remainder (0–15) as a hex digit.
3. Use the quotient for the next division.
4. Continue until the quotient is 0.
5. Write the remainders bottom‑to‑top.
Example (decimal 2004 → hex):
Division step Quotient Remainder Hex digit
2004 ÷ 16 125 4 4
125 ÷ 16 7 13 (D) D
7 ÷ 16 0 7 7
Result: 0x7D4.
Activity 1.5 – Hexadecimal → Decimal
Convert the following hex numbers to decimal:
1
2
Activity 1.6 – Decimal → Hexadecimal
Convert the following decimal numbers to hex (values given in transcript).

🧮 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

📁 Representing Text, Sound, and Images


Text
ASCII: 7‑bit code for 128 characters.
Unicode: Extends ASCII to many languages; often stored in UTF‑8 (variable‑length).

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

🌐 Network‑Related Number Representations


MAC address: 48‑bit identifier for a network interface, written as six groups of two hex digits (e.g., 00‑1C‑B3‑4F‑25‑FE).
IPv4 address: 32‑bit number, often shown in dotted‑decimal (e.g., [Link]) or as a single hexadecimal value.
IPv6 address: 128‑bit number displayed as eight groups of four hex digits separated by colons.

🎨 HTML Colour Codes


Colours are specified as six‑digit hex values #RRGGBB.
Each pair (RR, GG, BB) represents the intensity (0‑255) of red, green, and blue respectively.
Hex code Red Green Blue Colour example
#FF0000 255 0 0 Red
#00FF00 0 255 0 Green
#0000FF 0 0 255 Blue
#FF00FF 255 0 255 Fuchsia
#FF9966 255 153 102 Orange‑tan

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.

➕ Binary Addition & Carry 🚀


Definition – Carry is the value transferred to the next higher‑order bit when the sum of bits in a column exceeds the base (2 for
binary). Sum is the resulting bit written in the current column after accounting for any carry.

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

📈 Overflow in Fixed‑Size Registers ⚠️


Overflow occurs when the result of an arithmetic operation exceeds the maximum value that can be represented with the given
number of bits.

8‑bit unsigned register: maximum value 2 − 1 = 255


8

16‑bit unsigned register: maximum value 2 − 1 = 65, 535


16

32‑bit unsigned register: maximum value 2 − 1 = 4, 294, 967, 295


32

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.

🔀 Logical Bit Shifts ↔️


Logical shift moves all bits left or right, inserting zeros into the vacated positions. No sign bit is preserved; the operation works on
the raw bit pattern.

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

Diagram of left‑ and right‑shifts (8‑bit register):


The following image illustrates the effect of shifting the binary pattern 01110000₂ (decimal 112) left five places and right three places.
Explanation:
Left shift 5: 01110000 → 00000000; the original 1‑bits are shifted out, leaving all zeros (value 0).
Right shift 3: 01110000 → 00001110; the three least‑significant bits are lost, reducing the value from 112 to 14.
Practical examples (from the transcript):
Original (binary) Operation Result (binary) Decimal effect
01100100₂ (100) Left shift 2 10010000₂ 100 × 4 = 400

01100100₂ (100) Right shift 2 00011001₂ ⌊100/4⌋ = 25

01100100₂ (100) Right shift 4 00000110₂ ⌊100/16⌋ = 6 (bits lost)


Activity 1.11 – Shift the given binary numbers left/right the specified number of positions, then convert the result back to decimal and
note any loss of information.

🧭 Two’s Complement Representation 🔢


Two’s complement is the standard method for encoding signed integers in binary. The most‑significant bit (MSB) is the sign
bit: 0 = positive, 1 = negative.

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

Compute 2 − ∣N ∣, where n is the register width.


n
Example: Encode −1110 ​ in 8‑bit two’s complement.
Magnitude 11 = 00001011
10 2

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.

📚 Character Encoding – ASCII & Unicode 🔤


ASCII (American Standard Code for Information Interchange) uses 7 bits to encode 128 characters (0–127). Control codes (0–31)
manage device functions; printable characters occupy 32–126.

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.

🎧 Digital Sound Representation 🔊


Sampling converts a continuous (analogue) sound wave into a discrete sequence of amplitude values.

Sampling rate (samples / second, Hz) determines temporal resolution.


Bit depth (bits / sample) determines amplitude resolution.
File‑size formula:
Sampling rate (Hz)×Bit depth×Duration (s)
Size (bytes) = ​

Example from transcript:


A 60‑minute stereo CD track:
Sampling rate = 44 100 Hz
Bit depth = 16 bits
Channels = 2
44,100×16×60×60×2
Size = ​ ≈ 635, 040, 000 bytes ≈ 606 MiB
8

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) = ​

Example: A 2048 × 2048 image at 24‑bit colour depth:


2048×2048×24
​ = 12, 582, 912 bytes ≈ 12 MiB
8

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.

📦 Data Storage Units & File‑Size Calculations 💾


Unit (decimal) Symbol Bytes
Kilobyte kB 1 000
Megabyte MB 1 000 000
Gigabyte GB 1 000 000 000
Unit (IEC binary) Symbol Bytes
Kibibyte KiB 2
10
= 1 024

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.

Example calculations (from transcript):


1. Photo on a 1024 × 1030 sensor, 32‑bit depth
1024×1030×32
Bytes = ​ = 4, 423, 680 bytes ≈ 4.22 MiB
8

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.

📝 Practice Activities (selected)


Activity 1.8: Perform binary additions such as 1110₂ + 0100110₂.
Activity 1.9: Convert given decimal numbers (e.g., 9, 16, ‑17) to binary, add them, and verify against decimal sums.
Activity 1.10: Add binary pairs (e.g., 0111 + 1101) and comment on any overflow.
Activity 1.11: Shift specified binary numbers left/right three places; note the resulting decimal values and any lost bits.
Activity 1.12 & 1.13: Convert positive and negative decimal numbers to two’s‑complement binary, then reverse the process.
Activity 1.14: Translate given two’s‑complement binaries back to signed decimal values.
Activity 1.15: Define terms (colour depth, bitmap, sampling rate, etc.) and discuss how changing each parameter influences
file size.
Activity 1.16: Compute the storage required for a 1920 × 1536 image at 24‑bit depth; determine how many such photos fit on
a 6 GiB memory card.
These exercises reinforce the concepts of binary arithmetic, overflow, shifting, two’s complement, and data representation introduced
above.

📟 Binary Coded Decimal (BCD) 🧮


Definition – Binary‑coded decimal encodes each decimal digit (0‑9) separately using a fixed‑width binary code, typically 4 bits per
digit.

4‑bit BCD patterns (excerpt from the lecture):


Decimal digit BCD (4 bits)
0 0000
1 0001
2 0010
3 0011
4 0100
5 0101
6 0110
7 0111
8 1000
9 1001
Example conversion (decimal → BCD) – Convert 5 0 0 6 7 5 9 to BCD:
5 → 0101, 0 → 0000, 0 → 0000, 6 → 0110, 7 → 0111, 5 → 0101, 9 → 1001
Result: 0101 0000 0000 0110 0111 0101 1001
Example conversion (BCD → decimal) – BCD string 0110 0001 0010 represents the digits 6‑1‑2 → decimal 612.
Typical use – Digital clocks and calculators display decimal numbers directly because each digit can be driven by a separate
7‑segment display using its BCD code.

➖ Subtraction Using Two’s Complement 🧮


Definition – To subtract a binary number B from A, form the two’s‑complement representation of B (i.e., invert the bits and add 1)
and then add it to A. The final carry‑out is discarded.

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

3. Add the result to A.


4. If a carry out of the most‑significant bit occurs, ignore it.
5. The sum now represents A − B (negative if the sign bit is 1).

Worked Example (from transcript)


Subtract 68 from 95 (both decimal).
1. Binary forms (8‑bit):
95 → 01011111
68 → 01000100
2. Two’s complement of 68:
Invert → 10111011
Add 1 → 10111100
3. Add to 95:

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)

4. Drop the carry → 01011100 = 92 , the transcript’s stated answer.


10 ​

Practice Prompt (lecture)

Carry out the following binary additions/subtractions using the B‑bit column weighting (where B = 8):

Operation Binary operands Expected result (binary)


128 + ? 10000000 + ? —
0+0→? 00000000 + 00000000 —
11000 – ? 01100000 – ? —
(Students should apply the two’s‑complement method.)

📦 Data Transmission Basics 🌐


Definition – Data transmission is the movement of digital information between devices over a communication medium.

Key parameters (from the transcript):


Direction – simplex, half‑duplex, full‑duplex.
Method – serial (one bit at a time) or parallel (multiple bits simultaneously).
Synchronization – ensuring bits are received in the correct order.
Units – Kilobits per second (kbps) or Megabits per second (Mbps) measure bandwidth.

📡 Packet Structure and Switching 🚦


Packet Components
Component Typical contents Purpose
Header Source address, destination address, Enables routing, ordering, and integrity
sequence number, packet size (and checks
sometimes total‑packet count)
Payload Actual user data (often ~64 KiB) The information being transmitted
Trailer End‑of‑packet marker, error‑checking Signals packet end and assists error
value (e.g., CRC) detection

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.

Example Flow (illustrated in transcript)


1. A photograph is split into five packets.
2. Each packet follows a distinct path through the network.
3. At the destination, the router uses the sequence numbers to reorder them.

🔄 Serial vs Parallel Transmission 🔀


Feature Serial Parallel
Bits per transfer 1 Typically 8 (one byte)
Typical distance Long (e.g., USB, Ethernet) Short (e.g., on‑board CPU buses)
Risk of skew Low (single line) Higher – bits may arrive at different times
Hardware cost Fewer wires, cheaper More wires, more pins
Speed Slower per clock tick but can run at higher Faster per tick but limited by signal
clock rates; overall fast for long distances integrity over distance
Common uses USB, RS‑232, network cables CPU internal buses, older printer ports

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

🔌 Universal Serial Bus (USB) Overview 📎


Definition – USB is a standardized serial interface that supports power delivery and data transfer, capable of half‑ and full‑duplex
communication.

Cable composition (lecture diagram):


Wire colour Function
Red +5 V power
Black Ground
White Data + (D+)
Green Data − (D−)
Shield Electromagnetic shielding
Key characteristics (lecture notes):
Supports multiple data rates (e.g., USB 2.0 up to 480 Mbps, USB 3.0 up to 5 Gbps, USB‑C up to 10 Gbps).
Hot‑plug detection: voltage change on D+ / D− signals informs the host that a device has been connected,
prompting automatic driver loading.
Power delivery: up to 100 W (20 V × 5 A) with USB‑C, enabling charging of laptops.
Advantages – universal connector, backward compatible, combines power and data.
Drawbacks – limited cable length for high speeds, occasional need for hubs.

🛡️ Error Detection Techniques 🚨


Why Detect Errors?

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.

Common Methods (from transcript)


Technique Principle Typical use
Parity bit Adds a single bit so that the total number Simple serial links, early memory modules
of 1s is even (even parity) or odd (odd
parity).
Checksum Sums all data words (often modulo 2 ) 16
Internet Protocol (IP) headers
and transmits the result; receiver
recomputes and compares.
Cyclic Redundancy Check (CRC) Performs polynomial division on the Ethernet frames, USB packets
payload; the remainder is sent as the CRC
value.
Automatic Repeat Request (ARQ) Receiver requests retransmission when Reliable protocols like TCP
error detection fails.
Error‑correcting codes (ECC) Adds redundant bits that allow the RAM modules, deep‑space
receiver to correct certain bit errors (e.g., communication
Hamming code).

Example CRC Check (lecture)


Sender computes CRC for payload 10000011 00100110 (binary).
Trailer stores the CRC value (e.g., 0x3F).
Receiver recalculates CRC on the received payload; if the computed value ≠ trailer, the packet is flagged for retransmission.

📋 Sample Exam‑Style Questions (from transcript)


1. RLE Compression – An 8 × 8 bitmap contains 92 RLE values. If the original uncompressed file required 192 bytes, what is the
compression ratio?
Solution sketch: Ratio = 92/192 ≈ 0.48 (≈ 48 % of original size).
2. BCD Conversion – Convert the decimal number 375 into BCD.
Answer: 0011 0111 0101.
3. Two’s‑Complement Subtraction – Subtract 49 from 0x8D using two’s complement (8‑bit). Show the intermediate
two’s‑complement of 49 and the final result.
4. Packet Header Fields – List three pieces of information typically stored in a packet header and explain their purpose.
5. Serial vs Parallel – Explain why serial transmission is preferred for long‑distance links despite lower per‑clock bandwidth.
6. USB Hot‑Plug – Describe what electrical change the host computer detects when a USB device is connected.
7. Error Detection – A payload contains the bit pattern 11010110. Using even parity, what parity bit should be appended?
Answer: The number of 1s is 5 (odd), so the parity bit must be 1 to make the total even.
These questions reinforce the concepts introduced in this section and can be used for self‑assessment.

🔐 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.

Pros – Simple; no extra calculation required.


Cons – Doubles the traffic; if the echo itself is corrupted, the error may be misattributed.

🔢 Check Digits
Check digit – an extra digit (or character) appended to a numeric identifier that is computed from the other digits.

Common uses: ISBNs, VINs, credit‑card numbers, bar‑codes.


Check digits detect common entry mistakes such as a single‑digit error, transposition, or omission.
📚 ISBN‑13 (Modulo 10)
Algorithm (from the transcript):
1. Starting from the left, sum all digits in odd positions.
2. Sum all digits in even positions, multiply this sum by 3.
3. Add the two results together.
4. Compute the remainder modulo 10.
5. If the remainder is 0, the check digit is 0; otherwise the check digit = 10 − remainder .
Example – ISBN 978030640615
Odd sum = 9 + 8 + 3 + 6 + 6 + 1 = 33 Even sum
​ ​
= 7 + 0 + 0 + 4 + 0 + 5 = 16 Weighted even = 3 × 16 = 48 Total
​ ​
= 33

Resulting ISBN‑13: 9780306406159.


📚 Modulo‑11 (used for many product codes, VINs)
1. Assign weightings decreasing from the left (e.g., for an 8‑digit number: 8, 7, 6, 5, 4, 3, 2, 1).
2. Multiply each digit by its weight and sum the products.
3. Compute the remainder of the sum divided by 11.
4. The check digit = 11 − remainder; if the remainder is 0, the check digit is 0; if the remainder is 1, the check digit is usually
represented by ‘X’.
Example – Number 1234567 (weights 8‑1)
Sum = 1!×!8 + 2!×!7 + 3!×!6 + 4!×!5 + 5!×!4 + 6!×!3 + 7!×!2 = 8 + 14 + 18 + 20 + 20 + 18 + 14 = 112 Remainder
​ ​
= 112

Final code: 12345679.

📡 Automatic Repeat Request (ARQ)


ARQ – a protocol that combines error detection with retransmission control.

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.

📡 Parity Checking & Check Digits


Parity – a single extra bit added to each transmitted byte so that the total number of 1 bits matches the agreed‑upon rule (even or
odd).

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.

📶 Data Transmission Methods


Method Direction Typical use Key characteristic
Serial One bit at a time Long‑distance links (USB, Fewer wires, lower skew
Ethernet)
Parallel Multiple bits simultaneously Short‑range internal buses Higher speed but prone to
skew
Half‑duplex One way at a time, same Walkie‑talkies, some legacy Simpler hardware
channel networks
Full‑duplex Simultaneous two‑way Telephone, modern Ethernet Requires separate
transmit/receive paths

Skew – timing mismatch between parallel lines that can corrupt data if bits arrive at different times.

Choosing the Best Method for Rory’s Remote File Transfer


Scenario: Transfer a large file from a computer to a server 100 m away.
Optimal choice: Serial full‑duplex (e.g., Ethernet or fiber) because serial links tolerate longer distances, avoid skew, and
provide reliable bidirectional communication.

🔄 Duplex Transmission in Practice


Duplex transmission can be serial or parallel; the key is that both ends can send and receive simultaneously.
In a full‑duplex link, two separate signal paths (or differential pairs) allow independent streams, eliminating the need to wait
for the channel to become idle.

True/False statements (from lecture):

Duplex can be implemented with either serial or parallel – True.


Duplex always uses two separate wires – False (full‑duplex may use a single twisted pair with differential signaling).

🖥️ Serial vs. Parallel ICs


IC that sends multiple bits at once → parallel data transmission IC.
IC that sends one bit at a time → serial data transmission IC.

🔌 USB Connection Benefits


1. Power + Data on a single cable – simplifies wiring and allows devices (e.g., printers, external drives) to be powered directly
from the host.
2. Hot‑plug detection – the host senses voltage changes on the D+ / D‑ lines, automatically loads the appropriate driver
without rebooting.

🧠 CPU Architecture & von Neumann Model


von Neumann architecture – a design where program instructions and data share the same memory space, accessed via a single set
of buses.

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).

📡 System Buses & Memory Operations


Bus type Direction Typical width Function
Address bus Unidirectional (CPU → 16‑, 32‑, 64‑bit Carries memory addresses.
memory)
Data bus Bidirectional Same as address bus Transfers actual data or
instructions.
Control bus Bidirectional Few bits Sends control signals
(read/write, interrupt, clock).

Read Operation (using MAR & MDR)


1. MAR ← address (e.g., 1111 0001).
2. CPU asserts read on the control bus.
3. Memory places the contents at that address onto the data bus.
4. MDR ← received data.
Write Operation
1. MDR ← data to store (e.g., 1001 0101).
2. MAR ← target address (1111 1101).
3. CPU asserts write on the control bus.
4. Memory captures the data from the data bus and writes it to the specified address.

⏱️ 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.

🖥️ Instruction Set Overview


Instruction set – the complete collection of machine‑level commands a CPU can execute (e.g., ADD, JMP).

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.

Set‑Top Box Example

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

📊 Barcode Scanners (Input Devices)


Barcode scanner – an input device that converts a patterned series of dark and light bars into a digital representation of the
encoded number.
The diagram illustrates guard bars and the placement of numerical data within a typical linear barcode.
Operation – a light source (laser or LED) reflects off the barcode; a photodiode detects the reflected intensity, producing a
binary stream (1 = dark bar, 0 = space).
Uses – retail point‑of‑sale, inventory tracking, ticket validation.

📚 Practice Activities (selected)


Activity Objective
Parity & Check Digits Order the six statements about check‑digit computation;
compute parity for given bytes and identify errors.
Encryption Encode a short message with the symmetric key 136285;
describe how a public‑key exchange would secure the same
message.
Transmission Choice Justify the selection of serial full‑duplex for a 100 m file transfer;
contrast with parallel options.
CPU Cycle Trace the fetch‑decode‑execute steps for a sample instruction
(ADD R1, R2).
Embedded System Design Sketch a simplified block diagram for a smart lighting controller,
labeling sensors, controller, memory, and actuators.
Barcode Decoding Given a binary stream from a scanned barcode, translate it back
to the numeric code using the guard‑bar pattern.
These activities reinforce the concepts introduced in this section and prepare you for exam‑style questions.

📦 Barcodes & QR Codes 🚀


Barcode – a visual representation of numeric data using a pattern of alternating dark (absorbing) and light (reflecting) bars.

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.

Quick‑Response (QR) Codes 📱


QR code – a two‑dimensional matrix barcode consisting of many tiny dark and light squares (pixels).

Capacity – up to 4 296 alphanumeric characters (≈ 7 089 digits).


Key components
Three large corner squares provide alignment, size, and orientation detection.
Timing patterns run between corners to establish a coordinate grid.
Reading method – a smartphone camera captures the pattern; a QR‑reader app extracts the data (often a URL, telephone
number, or boarding‑pass information).
Advantage over 1‑D barcodes Explanation
Much higher data capacity Stores URLs, contact details, or whole documents.
Built‑in error correction Reed‑Solomon codes allow up to 30 % damage while still being
readable.
No specialised laser scanner needed Standard camera modules suffice.
Easy to embed in graphics Logos or images can be over‑laid (frame QR codes).
Disadvantages – multiple QR formats can cause compatibility issues; free generation tools can be abused to embed
malicious URLs or payloads.

📸 Digital Cameras & Image Capture


Digital camera – an embedded system that converts light into a digital image using a sensor array (CCD or CMOS).

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.

Dynamic microphone operation


1. Sound waves move a diaphragm attached to a coil.
2. The coil cuts through a static magnetic field, inducing a voltage (Faraday’s law).
3. The analog voltage is fed to an ADC, yielding a digital audio stream (e.g., 44.1 kHz, 16‑bit PCM).
Optical Mouse

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.

Technology Principle Typical use Pros Cons


Capacitive (surface) Human skin changes the Smartphones, tablets High clarity, multi‑touch Requires conductive
electrostatic field at the touch (no gloved
screen corners. fingers).
Capacitive (projective) Transparent electrode High‑end tablets, kiosks Supports stylus & Slightly higher cost.
matrix creates a 3‑D gloved hand,
field; touch disturbs it. multi‑touch
Infrared Array of IR LEDs and Large interactive Works with any object, Sensitive to ambient
photodiodes forms a displays resistant to scratches light, can be triggered
grid; interruption of accidentally.
beams indicates touch.
Resistive Two conductive layers ATMs, industrial panels Works with any pointer Lower optical clarity,
separated by a gap; (gloves, stylus) single‑touch only.
pressure forces contact,
creating a voltage
change.

📠 Scanners
2‑D Document Scanners

2‑D scanner – an optical device that converts a physical page into a digital image.

Scanning workflow (illustrated below):


1. Document placement – glass platen holds the sheet.
2. Illumination – bright LED or xenon lamp shines through the page.
3. Image capture – a moving scan head projects the light onto a CCD sensor array.
4. Focusing – lens focuses the reflected light onto the CCD.
5. Conversion – each CCD pixel creates a charge proportional to brightness; the ADC digitises these into pixel values.
6. Processing – software assembles the pixel matrix into a raster image (e.g., JPEG) and may apply OCR to extract text.

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.

Methods include structured light, laser triangulation, and time‑of‑flight.


The point cloud is processed into a CAD model or STL file, which can be fed to a 3‑D printer.
Applications
Airport security (passport photo matching).
Medical imaging (CT, MRI).
Industrial reverse engineering.

📺 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.

📚 Summary of Key Terms (Blockquotes)


Barcode – pattern of light/dark bars encoding numeric data, read by a photodiode array.

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.

🔴 Laser printer – how it works


Laser printer – a device that uses a rotating photoconductive drum, static electricity, and powdered toner to produce text and
images on paper.

Stage Action (as described)


1️⃣ Document data is sent to the printer driver and placed in a
printer buffer.
2️⃣ The drum receives a uniform positive charge as it rotates.
3️⃣ A laser beam scans the drum, discharging (making negative) the
areas that correspond to the image/text.
4️⃣ Positively‑charged toner (dry powder) adheres only to the
negatively‑charged portions of the drum.
5️⃣ A negatively‑charged sheet of paper rolls over the drum; toner
transfers from drum to paper.
6️⃣ The paper passes through a fuser – heated rollers melt the toner,
permanently fixing it to the paper.
7️⃣ A discharge lamp removes residual charge from the drum,
readying it for the next page.

⚖️ Inkjet vs. Laser – quick comparison


Feature Inkjet Laser
Print medium Liquid ink (droplets) Powdered toner
Typical use‑case High‑quality photos, low‑volume colour High‑volume text or colour flyers, office
jobs environments
Cartridge size Small, many colour cartridges Large toner cartridges (often > 1 kg)
Speed Slower for full‑page colour Very fast (multiple pages per minute)
Print quality Excellent colour gradients, good for Sharp text, solid colour blocks; colour
photos quality improving with newer models
Running cost Ink can be expensive per page Toner lasts longer; higher upfront cost but
lower per‑page cost

🛠️ 3D Printing (Additive Manufacturing)


3D printer – a machine that builds solid objects layer‑by‑layer from digital models, primarily using inkjet‑ or laser‑based processes.

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.

Typical 3D‑printing workflow


1. CAD modelling – design the part in a 3‑D modelling program (e.g., SolidWorks, Fusion 360).
2. Slicing – software converts the model into thin layers and generates G‑code or printer‑specific commands.
3. Material loading – appropriate powder, resin, or filament is prepared in the printer.
4. Layer deposition & solidification – each slice is built according to the sliced data (binder jet, laser, or UV cure).
5. Post‑processing – excess powder is removed, parts may be cured further, sanded, or metallised.

📺 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.

🔊 Audio Output – Loudspeakers


Loudspeaker – an electromechanical transducer that converts electrical audio signals into audible sound waves.

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.

🧭 Sensors & Actuators


📏 Sensor definition
Sensor – an input device that converts a physical quantity (temperature, pressure, light, etc.) into an electrical signal that can be
interpreted by a computer.
Analog sensors produce a continuously varying voltage/current; an ADC (Analog‑to‑Digital Converter) digitises the signal
for processing.

📊 Common sensor types


Sensor Measured quantity Typical application
Thermocouple Temperature Industrial furnace monitoring
RTD / Thermistor Temperature HVAC control
Photodiode / Light sensor Light intensity Automatic brightness adjustment
Microphone Sound pressure Voice‑activated assistants
Accelerometer Acceleration / vibration Smartphone orientation
Proximity (IR / ultrasonic) Distance Automatic door opening
Pressure transducer Fluid/air pressure Hydraulic system monitoring
Gas sensor Specific gas concentration (CO₂, O₂, etc.) Environmental monitoring

⚙️ 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.

📊 Monitoring vs. Control Systems


🔎 Monitoring (data acquisition)
Sensors continuously sample the environment.
The raw analogue signal → ADC → digital value.
Microprocessor stores or displays the reading and may compare it against preset thresholds.
If a reading falls outside acceptable limits, an alert (sound, visual indicator, network message) is generated.
Typical monitoring examples
Domain Parameter Sensor used
Healthcare Heart rate, temperature ECG electrodes, thermistor
Security Motion, glass breakage PIR sensor, acoustic sensor
Environment River pollution levels Conductivity & turbidity probes
Industry Engine temperature Thermocouple
Infrastructure Power line voltage Voltage divider + ADC

🔄 Control (feedback loop)


1. Sensor measures the current state.
2. ADC digitises the measurement.
3. Microcontroller compares the measurement to a set‑point (desired value).
4. If deviation exists, the controller computes an actuation command (often using PID logic).
5. DAC (or direct digital output) drives an actuator to correct the condition.
6. The process repeats at a defined sampling rate, stabilising the system.
Control‑system examples
Application Measured variable Actuator
Street lighting Ambient light level Relay that powers the lamp
Anti‑Lock Braking System (ABS) Wheel rotation speed (magnetic sensor) Modulated brake‑pressure valves
Central heating Water temperature Boiler valve & pump (via DAC)
3D printer extrusion Filament feed rate Stepper motor controlling the extruder
Drone flight stabilization Gyro angle Brushless motors adjusting thrust

📡 Real‑World Integrated Examples


🔐 Security system (monitor‑only)
Input: keypad (password), infrared motion sensor, acoustic sensor, pressure mat.
Processing: ADC converts sensor signals; microprocessor continuously compares against stored patterns.
Output: If any sensor exceeds its threshold, a DAC drives a siren and flashing lights; the system remains active until a correct
password is entered.

🌃 Street‑light automation (monitor + control)


1. Light sensor → ADC → digital lux value.
2. Microcontroller checks if value < threshold (night).
3. If true, it sends a digital high to a relay (actuator) turning the lamp on for a fixed 30 min block, preventing flicker during brief
cloud cover.
4. After the interval, the sensor is re‑sampled.

🚗 Anti‑Lock Braking System (ABS)


Wheel‑speed sensors (magnetic) feed rotational speed to the microcontroller.
If a wheel decelerates too quickly (potential lock), the controller reduces brake pressure to that wheel via a hydraulic
modulator while increasing pressure on the others, maintaining traction.

♨️ Central heating loop


1. Thermostat sensor → ADC → current room temperature.
2. Desired temperature is stored as the set‑point.
3. If measured < set‑point, the controller issues a DAC‑driven command to open the gas valve and start the water pump.
4. When temperature reaches the set‑point, the valve closes and the pump stops.

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.

🤖 Process Control Using Sensors & Actuators


Sensor: a transducer that converts a physical variable (e.g., temperature, pH) into an electrical signal.

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.

Chemical Reactor Example


Measured variable Sensor reading → ADC CPU decision (pre‑set limits) Actuator command → DAC
Temperature > 70 °C Digital “high” Turn heater OFF 0 V to heater control line
Temperature < 0 °C Digital “low” Turn heater ON 5 V to heater control line
pH < 3.5 Digital “acidic” Open acid‑addition valve 5 V to valve driver
pH ≥ 3.5 Digital “neutral/alkaline” Close valve 0 V to valve driver
The loop repeats continuously while the controller is powered, providing closed‑loop regulation of both temperature and acidity.

🌱 Greenhouse Environmental Control


Five sensors are typically deployed: humidity, soil moisture, temperature, pH, and light intensity.

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.

Humidity‑only flow (illustrative)


1. Humidity sensor → ADC → digital humidity %.
2. If % < set‑point → DAC drives a motor that opens a window, lowering humidity.
3. If % > set‑point → DAC opens a sprinkler valve to mist water, raising humidity.
4. The process repeats as long as the system is powered.
The same pattern applies to the other four variables, each with its own actuator (heater, dehumidifier fan, nutrient pump, grow‑light
dimmer, etc.).

📊 Monitoring vs. Control


Monitoring: passive observation of sensor data; alerts are generated but no automatic corrective action is taken.

Control: active adjustment of actuators based on sensor feedback, forming a closed‑loop system.

Aspect Monitoring Control


Goal Detect abnormal conditions Maintain a target condition
Action Raise alarm, log event Modify hardware (heater, valve, motor)
Example Display reactor temperature on a Shut off heater when temperature
dashboard exceeds 70 °C

💾 Data Storage Overview


The diagram below contrasts primary memory (directly addressable by the CPU) with secondary storage (non‑volatile, accessed via
I/O controllers).
The chart highlights that primary memory (RAM, ROM, cache) is fast and directly addressable, whereas secondary storage (HDD, SSD,
optical discs) is slower, non‑volatile, and accessed through block‑level I/O.
Attribute Primary Memory Secondary Storage
Direct CPU addressing Yes No
Volatility Volatile (RAM) or non‑volatile (ROM) Non‑volatile
Typical speed nanoseconds (cache) → microseconds milliseconds (HDD) → microseconds (SSD)
(RAM)
Typical capacity MB–GB GB–TB
Example devices RAM, ROM, cache HDD, SSD, DVD, USB flash drive

🧠 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.

Solid‑State Drive (SSD)


Stores data in NAND flash cells composed of a floating‑gate transistor and a control gate.
Write mechanism: electrons are injected onto the floating gate through a high‑field tunnel; the trapped charge represents a
binary “1”.
Advantages: no moving parts → negligible latency, lower power, higher durability, silent operation.
Drawbacks: limited write‑endurance (typically ~10⁴ – 10⁵ program/erase cycles per block) and higher cost per GB compared
with HDDs.

Optical Media (CD / DVD / Blu‑ray)


Media Laser wavelength Typical capacity (single Data rate
layer)
CD 780 nm (red) 700 MB ~10 Mbps
DVD 650 nm (red) 4.7 GB ~10–11 Mbps
Blu‑ray 405 nm (blue) 25 GB ~36 Mbps
Data are encoded as pits (low reflectivity) and lands (high reflectivity) along a continuous spiral track.
Blu‑ray’s shorter wavelength permits smaller pits and tighter track spacing, yielding roughly five‑times the storage of a DVD.

🖥️ 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

Benefits & Drawbacks


Benefit Drawback
Scalability – pay‑as‑you‑go storage Internet dependence – access requires a stable connection
Redundancy – data replicated across sites Security concerns – loss of direct physical control
Cost‑effective for occasional large backups Potential data loss – provider outages or breaches

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.

📡 Monitoring & Control in Embedded Systems


Function Example device Sensor used Actuator driven
Reactor temperature monitor Chemical plant controller Thermocouple → ADC Alarm LED, shutdown valve
Gas‑pressure safety Industrial reactor Pressure transducer → ADC Gas pump (opened when
pressure > threshold)
Traffic‑light controller City intersection Infrared vehicle detector → LED colour sequence via driver
ADC transistors
Soil‑acidity regulator Automated irrigation system pH probe → ADC Acid‑injection valve via DAC
(greenhouse)
These examples illustrate how the same sensor → ADC → CPU → DAC → actuator pipeline underpins a wide variety of real‑world control
tasks.

📁 Virtual Memory & Storage Environment 🗂️


Virtual memory lets a computer use disk space (swap space) to extend the apparent size of RAM, enabling programs to run even
when physical RAM is exhausted.

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.

🔎 Storage Terminology Matching 🧩


The left‑hand column lists common storage‑related terms; the right‑hand column gives their definitions.

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).

🖥️ RAM vs. ROM – Four Key Differences 📚


RAM (Random‑Access Memory) is volatile and writable; ROM (Read‑Only Memory) is non‑volatile and primarily read‑only.

Aspect RAM ROM


Volatility Loses data when power is removed. Retains data without power.
Write capability Frequently written and overwritten. Typically programmed once (or a few
times).
Typical use Holds program code and data while Stores firmware/bootloader that must
executing. persist.
Speed Faster access (nanoseconds to Slower to write; read speed comparable
microseconds). to RAM but not as fast as cache.

📀 Solid‑State Memory Vocabulary 🧩


The paragraph in the transcript describes how SSDs work; the missing words are filled with the following terms (each used once):
NAND, cell, floating‑gate, transistor, threshold, program, erase, page, block, controller.

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.

💽 SSD Advantages & One Disadvantage 🚀


Advantages of SSDs over HDDs (especially for laptops):

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.

🌐 Network Hardware – NIC & MAC 📡


🔌 Network Interface Card (NIC)
A NIC is the hardware component that connects a device to a network (wired or wireless). It contains a unique Media Access
Control (MAC) address assigned at manufacture.

Wired NICs use Ethernet ports (RJ‑45).


Wireless NICs (WNICs) embed a radio transceiver; they often appear as USB dongles or internal modules.

📟 MAC Address Details


A MAC address is a 48‑bit identifier written as six groups of hexadecimal digits (e.g., 00‑1C‑B3‑4F‑25‑FE).

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.

Types of MAC Addresses


Universally Administered Address (UAA) – set by the factory; most common.
Locally Administered Address (LAA) – can be changed by the user or software. LAA is used when:
Legacy mainframe software requires a specific MAC format.
A network filter blocks certain OUIs, so a device must spoof a permitted range.
Organizations need to anonymise hardware for privacy or testing.

Changing a MAC to an LAA can cause address collisions if the new value is not unique on the local segment.

🌍 IP Addressing – IPv4, IPv6, Private & Public 🚦


📄 IPv4 vs. IPv6
Version Bits Notation Example
IPv4 32 Dotted decimal (four octets) [Link]
IPv6 128 Eight groups of hexadecimal [Link]
separated by colons
IPv4’s 32‑bit space limits the total number of unique addresses, prompting the transition to IPv6, which vastly expands the
address pool and adds built‑in authentication checks.

🔐 Public vs. Private IP Addresses


Private IP – unique within a local network (e.g., [Link], [Link]). The same private range can be reused on separate
LANs.
Public IP – assigned by the ISP; globally unique across the Internet. All devices behind a NAT router share the router’s public
IP while retaining distinct private IPs.

🔁 Static vs. Dynamic IP Addresses


Property Static IP Dynamic IP
Assigned by ISP (or network admin) permanently ISP via DHCP each time the device
connects
Typical use Servers, VPN endpoints, remote‑access Home computers, smartphones, laptops
devices
Change frequency Never changes (unless manually May change on each reconnection or
re‑assigned) lease renewal
Management overhead Higher – requires manual configuration Lower – automated by DHCP server

DHCP Workflow (Dynamic Allocation)


1. Device broadcasts a DHCPDISCOVER.
2. DHCP server replies with DHCPOFFER (proposes an IP lease).
3. Device sends DHCPREQUEST to accept.
4. Server confirms with DHCPACK; lease timer starts.

🛣️ Routers & Packet Forwarding 🌐


A router connects multiple networks (e.g., a LAN to the Internet) and forwards packets based on destination IP addresses.

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.

🔌 Ports & Interfaces – USB & HDMI ⚡


🔗 USB (Universal Serial Bus)
USB provides asynchronous serial data transfer and power over a single cable.

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).

📺 HDMI (High‑Definition Multimedia Interface)


HDMI carries both high‑definition video and audio in a single digital stream.

Replaces the analog VGA interface.


Supports resolutions up to 4K @ 120 Hz (and higher with HDMI 2.1).
Used for monitors, TVs, projectors, and VR headsets.

📶 Wired vs. Wireless Networks – Comparison 📡


Feature Wired (Ethernet, Fiber, Coax) Wireless (Wi‑Fi, Bluetooth)
Medium Copper or glass cable Radio waves (2.4 GHz, 5 GHz, etc.)
Bandwidth Up to 100 Gbps (fiber) Wi‑Fi 6 up to 9.6 Gbps; Bluetooth 5.2 up to
2 Mbps
Latency Typically lower (µs) Slightly higher (ms) due to contention
Security Physical access needed to tap Requires encryption (WPA3, etc.)
Mobility Fixed; limited to cable length High; devices can move within coverage
area
Installation cost Cable, conduit, and switches Access points and routers; lower cabling
cost

📡 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)

Static vs. Dynamic IP Addresses


Aspect Static Dynamic
Stability Permanent; ideal for servers May change; ideal for client devices
Configuration Manual entry or reserved DHCP lease Automatic via DHCP
Cost Often higher (ISP may charge) Usually included in standard service
Use Cases Web servers, VPN gateways, Home PCs, smartphones, laptops
remote‑access devices

Wired vs. Wireless (Key Decision Factors)


Decision Factor Wired Wireless
Reliability Very high (no RF interference) Dependent on signal strength and
congestion
Scalability Limited by cabling infrastructure Easy to add devices without new cables
Security Physical security required Must employ encryption and
authentication
Mobility None Full mobility within coverage area

📋 Activity Prompts (Section 3.8)


1. Define the following terms (use blockquotes for each): NIC, MAC address, Router, DHCP server.
2. List two features of dynamic IP addressing and two features of static IP addressing.
3. Explain why an organization might replace a device’s factory‑set MAC (UAA) with a locally administered MAC (LAA).
4. Compare MAC addresses and IP addresses in a short paragraph, citing their layers, format, and scope.
These prompts reinforce the networking concepts introduced above and build on the earlier discussion of binary/hexadecimal
representations (e.g., MAC addresses use hex notation).

🖥️ System Software Overview


System software is a collection of programs that enable the hardware to function correctly and provide a platform for application
software to run.

The infographic below breaks the major categories down:

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.

Typical utilities (as listed in the transcript) include:


Virus checkers (antivirus)
Defragmentation tools
Disk analysis / repair utilities
File compression programs
Backup software (including screensavers that double as lock screens)

🦠 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.

On SSDs this is unnecessary because there are no moving heads.


The transcript illustrates fragmentation with a 12‑sector disk:
Step Disk layout (sectors)
Initial File 1 occupies all 12 sectors.
After deletion & extension File 2 is removed, File 1 is extended into sectors 10‑11, leaving
gaps.
Further writes New files occupy scattered free sectors, increasing
fragmentation.
After defragmentation All files are reordered into contiguous blocks; empty sectors are
grouped together.
This re‑ordering dramatically speeds up data access on HDDs.

💾 Backup Software
Backup utilities create duplicate copies of important data to protect against loss.

Three‑tier strategy (as recommended):


1. Current version – stored on the internal HDD/SSD.
2. Local copy – saved to a portable device (USB stick or external HDD).
3. Remote copy – stored off‑site, typically in the cloud.
Windows backup features
Restore points – snapshot of system state for rollback after a failure.
File History – incremental snapshots of user files; retains versions indefinitely unless settings are changed.
macOS backup (Time Machine)
Hourly backups for the past day, daily for the past month, and weekly for older data.
When the backup disk fills, the oldest backups are automatically removed.

� 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.

🏁 Operating System Fundamentals


An operating system (OS) hides hardware complexity and provides a stable environment for applications.

Core functions (as shown in the flowchart below):

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.

👤 Human‑Computer Interface (HCI)


Interface Advantages Disadvantages
Command‑Line Interface (CLI) Precise, scriptable, low overhead Steep learning curve, many commands to
remember
Graphical User Interface (GUI) Intuitive icons, drag‑and‑drop, Higher resource usage, less direct control
multitasking windows
Touch‑based (post‑WIMP) Natural gestures (pinch, rotate) on Limited precision for some tasks, may
mobiles/tablets need stylus

🧠 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).

Consequences of proper memory management:


Prevents data loss and security breaches caused by overlapping memory.
Avoids system crashes due to illegal memory accesses.

🔐 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.

📟 Hardware Peripheral Management


The OS communicates with I/O devices through device drivers, queuing requests and using buffers to smooth mismatched data
rates.

Example – printer management:


1. Printer driver loads into RAM.
2. Document data is placed in the printer buffer.
3. If the printer is busy, the job joins the print queue.
4. The driver sends control commands (e.g., start/stop) and handles error messages or interrupts from the printer.

📁 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.

⏱️ Interrupts & Buffers


Interrupts temporarily suspend the current CPU task to service a higher‑priority event (hardware fault, I/O request, user keystroke,
etc.).

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.

The OS assigns priorities; a low‑priority task may be pre‑empted by a higher‑priority one.


Time slicing gives each process a quantum of CPU time.
Proper multitasking improves overall throughput and keeps the system responsive, especially when combined with efficient
memory and interrupt management.

👥 Management of User Accounts


Modern OSes support multiple user accounts, each with its own settings, files, and permissions.

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).

🖥️ BIOS, EEPROM, and CMOS


The BIOS (Basic Input/Output System) is firmware stored in EEPROM (Electrically Erasable Programmable ROM).

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.

📊 Summary Flow of System Software


System software (compilers, linkers, drivers, utilities, OS) provides the foundation for application software.
The OS mediates between CPU and all software/hardware components, handling memory, files, security, interrupts, and
multitasking.
Utilities keep the system healthy (antivirus, defragmentation, backups).
Device drivers and BIOS enable the OS to talk to physical devices.
These interconnected layers ensure that a computer can reliably execute user programs while protecting data and hardware resources.

💻 Programming Languages: High‑Level vs Low‑Level


High‑level languages let programmers concentrate on the problem to solve rather than the details of the computer hardware.
Low‑level languages are closely tied to a specific processor architecture; they expose the hardware’s instruction set directly.
High‑Level Languages
Portability – the same source file can be compiled on many different machines (e.g., a Java program runs on Windows,
macOS and Linux).
Readability – statements resemble natural English, making them easier to understand, debug and maintain.
Typical uses – application software, web development, data analysis, scientific computing.
Common examples – C++, Java, Python, Visual Basic, Pascal, Delphi.
Sample high‑level statement (adds two numbers):

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):

0C0l 0coicolc 01n0 0C01coii 0o0c 0o011010

Assembly snippet (adds two numbers) and its meaning:

LDA FIRST ; load variable FIRST into the accumulator


ADD SECOND ; add variable SECOND to the accumulator
STA SUM ; store accumulator result into variable SUM

LDA = Load Accumulator


ADD = Add to Accumulator
STA = Store Accumulator
Understanding the three‑statement sequence requires knowing the processor’s accumulator model.

🛠️ Translators: Compilers, Interpreters, Assemblers


Translators convert human‑readable program text into the binary instructions a computer can execute.

Translator What it processes Output Typical workflow


Compiler Entire source file written in a Executable machine‑code file 1️⃣ Scan source → 2️⃣ Optimize
high‑level language (e.g., [Link]) → 3️⃣ Emit machine code → 4️⃣
Link → 5️⃣ Produce executable
Interpreter One statement at a time from Direct execution of the 1️⃣ Read statement → 2️⃣
a high‑level language statement (no permanent Execute immediately → 3️⃣
binary file) Proceed to next statement;
stop on error
Assembler Assembly language source Machine‑code object file 1️⃣ Translate each mnemonic →
2️⃣ Resolve addresses → 3️⃣
Output binary code

Advantages & Disadvantages


Translator Advantages Disadvantages
Compiler • Faster runtime (code is already native) • Longer development cycle (compile
• One‑time translation; no interpreter before testing)
overhead • Less flexible for rapid prototyping
Interpreter • Immediate feedback; great for learning • Slower execution
and scripting (statement‑by‑statement translation)
• No separate build step • Re‑interpretation each run
Assembler • Full control over hardware; optimal • Very hardware‑specific; poor portability
performance • Steeper learning curve
• Small code size

📦 Integrated Development Environments (IDEs)


An IDE bundles tools that streamline writing, testing and debugging programs.

Feature How it helps the developer Typical example


Code editor Single window for creating and editing Visual Studio’s editor, PyCharm’s editor
source files; syntax highlighting reduces
visual noise.
Translator (compiler / interpreter) One‑click “run” button automatically Run button in IntelliJ IDEA (uses javac
compiles or interprets the current file. under the hood)
Debugger Allows single‑stepping, setting Visual Studio debugger shows variable
breakpoints, and inspecting variable watch windows
values at runtime.
Error diagnostics & auto‑correction Flags syntax errors as you type and PyCharm underlines undefined variables
suggests fixes, catching many bugs before and offers quick‑fixes
compilation.
Auto‑completion Predictive text completion for keywords, VS Code suggests println() after typing
function names and variable identifiers, [Link].
speeding up coding.
Pretty‑printing Colours and indents code automatically, Eclipse colour‑codes strings, keywords,
improving readability (also called “syntax and comments
colouring”).
Auto‑documenter Generates documentation stubs (e.g., PyCharm can create docstrings for a new
Javadoc) from function signatures and function
comments.

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.

⚡ Interrupts in the Fetch‑Decode‑Execute Cycle


An interrupt is a signal that temporarily suspends the CPU’s current operation so that a higher‑priority event can be serviced.

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

3. IDE Feature Checklist


Feature Description Benefit
Code editor Syntax‑highlighted editing pane Reduces visual errors
Translator (compiler / interpreter) One‑click build/run Streamlines workflow
Debugger Breakpoints, watch windows, step Finds logical bugs efficiently
execution
Error diagnostics Real‑time linting & suggestions Catches mistakes early
Auto‑completion Context‑aware suggestions Speeds typing, avoids typos
Pretty‑printing Colouring & indentation Improves readability
Auto‑documenter Generates stubs for comments / docs Encourages good documentation practice

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.

🍪 Cookies – Session vs Persistent


Cookie – a small piece of data stored by a web browser that a server can read on subsequent requests.

🔹 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.

🔹 Persistent (Permanent) Cookies


Lifetime – written to the user’s hard‑drive and remain until the expiry date is reached or the user manually deletes them.
Content – can store login credentials, user preferences, or personalised settings that the user has previously supplied.
Security note – legitimate sites should encrypt any personal data stored in a cookie to prevent unauthorised third‑party
access.
Regulatory practice – many jurisdictions require persistent cookies to be deactivated after six months even if the set expiry
date is later.
Feature Session Cookie Persistent Cookie
Storage location In RAM (temporary) On hard‑drive (file)
Duration Until browser closed Until expiry or manual deletion
Typical data Session‑ID, cart token Login token, language preference, saved
form fields
Privacy impact Low (no personal data) Higher – can be used for tracking across
visits
Example use “Keep me logged in” for a single visit Remember username & password for
future logins

💰 Digital Currency & Cryptocurrency


Digital currency – money that exists only in electronic form; it has no physical notes or coins.

📄 What is Digital Currency?


Exists purely as data on computer systems (e.g., bank‑account balances, mobile‑payment apps).
Transactions are transferred between accounts via online banking, payment apps (PayPal, Apple Pay), or other electronic
services.
Relies on centralised banking infrastructure: each transaction must be validated by the issuing bank.

🔐 Cryptocurrency – decentralised alternative


Aspect Traditional Digital Currency Cryptocurrency
Authority Central bank or financial institution No central authority; governance by the
community via protocol rules
Transaction validation Bank’s internal ledger Blockchain consensus (proof‑of‑work or
other mechanisms)
Transparency Internal, not publicly visible All transactions are publicly recorded on
the blockchain
Security model Protected by the bank’s security systems Cryptographic hashes & distributed ledger
make tampering extremely difficult
Examples Online banking transfers, PayPal balances Bitcoin, Ethereum, other crypto‑coins

⛓️ 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.

⛏️ Proof‑of‑Work & Miners


Proof‑of‑Work (PoW): a computational puzzle that requires a certain amount of processing time; ensures that adding a
block is deliberately slow.
Miners: participants who perform the PoW calculation; they receive a block reward (new cryptocurrency units) plus any
transaction fees.
Because many miners compete, the network collectively enforces a steady rate of block creation and prevents any single
actor from monopolising the ledger.

📊 Visualising a Chain (Figure 5.9)


Genesis block (block 1) has no previous‑hash value.
If an attacker alters the data in block 2, its hash changes (e.g., from 6AB1 to something else). Block 3 still contains the old
previous‑hash (6AB1), so the chain is broken and nodes reject the tampered block.
The need to recompute PoW for every subsequent block makes such an attack practically impossible.

🛡️ 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.

Wired: a sniffer taps the Ethernet cable and records packets.


Wireless: wardriving (using a laptop, antenna, GPS) captures Wi‑Fi traffic from nearby access points.
Defence: use strong encryption (WPA3 for Wi‑Fi, TLS/HTTPS for web traffic), firewalls, and avoid unsecured public Wi‑Fi
for sensitive transactions.
🚨 Distributed Denial‑of‑Service (DDoS)
DDoS attack – flooding a target server or network with massive amounts of traffic from many compromised machines,
overwhelming legitimate requests.

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.

📧 Phishing & Pharming


Phishing – fraudulent emails or messages that mimic a trusted entity to trick users into revealing credentials or clicking malicious
links.

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.

Achieved via DNS cache poisoning or compromised DNS servers.


Mitigation: keep browsers and OS patched, use DNSSEC where available, verify the spelling of URLs, and rely on
HTTPS/TLS certificates.

📋 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.

🕵️ Social Engineering & Threat Landscape


Social engineering is the manipulation of users into divulging confidential information or performing actions that compromise
security.

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.

👥 Access Levels & Permissions


Access levels define what data or functions a user may read, modify, or delete within a computer system.

Role‑based hierarchy (Figure 5.13):


Administrator / Consultant – full read/write/delete rights.
Standard user – limited to necessary operations.
Cleaner / Guest – read‑only or no access to sensitive records.
Database context: different views/tables are exposed according to a user’s role, preventing accidental or malicious data
loss.
Social‑network privacy tiers:
Tier Who can see the data
Public Anyone on the Internet
Friends Only connections the owner has approved
Custom Owner selects specific friends or excludes certain people
Only me Solely the owner
These settings replace passwords for many platforms, allowing granular control over personal content.

🛡️ 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.

🔐 Authentication & Password Hygiene


Authentication proves that a user is who they claim to be.

Factors of authentication
Something you know – password, PIN.
Something you have – mobile phone, security token.
Something you are – biometric trait (fingerprint, retina).

Password best practices


Avoid common words or personal data (e.g., favourite colour).
Include ≥ 1 uppercase, ≥ 1 digit, ≥ 1 special character.
Example of a strong password: Sy12@#TT9Okj-0
Example of a weak password: GREEN
Systems typically enforce:
1. Password confirmation (enter twice).
2. Limited attempts (often three) before lockout.
3. Password reset via email link (one‑time token).

👆 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.

Typical flow for an online purchase:


1. User enters username & password (knowledge factor).
2. System sends a one‑time eight‑digit PIN to the user’s registered mobile device (possession factor).
3. User inputs the PIN, completing the transaction.
This combines “something you know” with “something you have,” dramatically reducing the risk of account takeover.

🔄 Automatic Software Updates


Automatic updates keep operating systems and applications current by applying patches without user intervention.

Advantages: timely security patches, performance improvements, new features.


Potential downside: an update may introduce bugs or incompatibilities, possibly requiring a rollback to a prior version.
Update scheduling options typically include:
Schedule Description
Automatic (nightly) Installs during off‑hours; minimal user impact.
Manual User decides when to apply each patch.
Deferred Updates are downloaded but installed later, allowing testing.

📧 Email Phishing Detection


Phishing emails masquerade as legitimate messages to steal credentials or deliver malware.

Checklist before clicking any link


1. Spelling & grammar – reputable organisations proof‑read; frequent errors signal fraud.
2. Tone – urgent or threatening language (“Your account will be closed”) is a red flag.
3. Sender address – verify the domain after the @ matches the official brand (e.g., @[Link], not @[Link]).
4. Link destination – hover to reveal the true URL; mismatched domains indicate phishing.
Example screenshot

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).

Types: hardware appliance, software service, or OS‑integrated module.


Core functions:
1. Packet filtering – applies rule‑sets to allow or block traffic.
2. Logging – records traffic for later analysis.
3. Application control – blocks specific programs (e.g., automatic updates) from accessing the Internet.
4. IP blacklisting – denies connections from known malicious addresses.
Firewalls cannot stop internal threats (e.g., a compromised employee’s device) or users who deliberately disable them.

🌐 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.

Key options across browsers and social platforms:


Setting Effect
Do‑Not‑Track Requests sites not to collect browsing behaviour.
Cookie control Limits storage of tracking cookies; can block third‑party cookies.
Location sharing Disables automatic GPS data transmission.
Saved payment methods Prevents auto‑fill of credit‑card details on untrusted sites.
Proper configuration reduces exposure to data harvesting and credential theft.

🔐 Secure Sockets Layer (SSL) & Transport Layer Security (TLS)


SSL/TLS are cryptographic protocols that protect data exchanged between a web browser and a server.

SSL vs. TLS


TLS is the modern successor to SSL, offering:
Extensible authentication methods.
Session caching to speed up repeated connections.
Separation of the handshake (authentication) from the record layer (data transport).

TLS handshake (seven stages)


1. Client hello – browser sends supported TLS version and cipher suites.
2. Server hello – server selects version/cipher and returns its digital certificate (signed by a trusted Certificate Authority).
3. Certificate validation – client checks the CA signature, expiration dates, and domain match.
4. Pre‑master secret generation – client creates a random value, encrypts it with the server’s public key, and sends it.
5. Master secret derivation – both sides compute a shared session key from the pre‑master secret.
6. Finished messages – each side confirms that the handshake was successful using the session key.
7. Secure data transfer – all subsequent HTTP traffic is encrypted with the session key.
When a site displays https:// and a padlock icon, the browser indicates a valid SSL/TLS certificate is in use.

📋 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.

🔐 Cryptography & Blockchain 🧩


Cryptography – the protection of data/information by using coding techniques; it normally involves encryption (transforming
plaintext into ciphertext) and decryption (reversing the process).

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, Packet Sniffing & Wardriving

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.

Denial‑of‑Service (DoS) & Distributed DoS (DDoS)

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).

📧 Social Engineering & Phishing


Phishing – sending legitimate‑looking emails that trick recipients into revealing personal details or credentials.

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.

🔐 Authentication & Access Control


Authentication factors
Factor Example
Something you know Password, PIN
Something you have Mobile phone (receives OTP), security token
Something you are Fingerprint, retina pattern, voice

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 & Patching

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.

Feature Typical rule


Port filtering Allow inbound HTTPS (port 443) only; block all other inbound
ports.
Stateful inspection Track connection state; only allow return traffic for established
sessions.
Application control Block known malicious executables or restrict social‑media apps.

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).

Secure Sockets Layer (SSL) & SSL Certificate

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.

📋 Exam‑Style Questions & Activities


1. Cookie concepts – Define a cookie. Distinguish between a session cookie and a persistent cookie, and give three examples
of each.
2. Spyware mitigation – Explain how spyware obtains data. Identify one method an online bank could use to reduce spyware
impact during login, and describe how it works.
3. Firewall protection – Describe how a firewall helps protect against unauthorised data access. List two additional security
measures the company could implement.
4. Matching activity – Connect each of the six statements on the left with the appropriate computer‑security term on the right
(e.g., “Manipulating people to break security procedures” ↔ social engineering).
5. Two‑step verification ordering – Arrange the following steps of a two‑step verification flow in the correct sequence:
User enters password →
System sends one‑time code to device →
User enters one‑time code →
System authenticates and grants access
6. Fingerprint‑recognition scenario – A school replaces manual attendance with fingerprint scanners. Explain how fingerprint
recognition works and why it reliably identifies the attending students.
7. Social‑engineering stages – Outline the four stages a cyber‑criminal follows when using social engineering to target an
individual.
8. Digital‑currency vs. fiat – Compare digital currency with traditional fiat money. Explain how blockchain technology could
protect both a company and its customers from fraud.
9. HTML structure – Briefly describe what is meant by “HTML structure” when building a web page.
10. SSL process – Detail the steps of an SSL handshake and how each step contributes to a secure connection.

These notes expand on the cybersecurity terminology introduced earlier (cryptography, binary concepts, etc.) and integrate the new
material into a single, continuous study guide.

🤖 Automated Systems in Real‑World Applications


Example 6 – Garden lighting & fountain display
Sensors (light sensor, motion detector) feed data to a microprocessor.
When ambient light falls below a threshold, the processor activates an array of LEDs in the garden and starts the
water‑fountain show.
If a person enters the garden, the motion detector triggers the lights to stay on and may dim them for a dramatic effect.

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

Example 7 – Pharmaceutical laboratory experiment


A microcontroller reads the colour of the reaction mixture from a colorimeter.
When the mixture reaches a bright orange hue, the controller opens a solenoid‑actuated tap to stop the addition of reagents.
The whole process runs without human intervention, allowing multiple experiments to be monitored simultaneously.

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

Activity 6.7 (brief)


Identify suitable sensors for a train, a vaccine‑mixing line, and an art‑gallery lighting display.
List two advantages and two disadvantages of automating each application.

🧠 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.

🛠️ Core Characteristics of a Robot


Characteristic Description
Sensing Detects the environment via light, pressure, temperature,
acoustic, or proximity sensors.
Processing A microprocessor or embedded computer interprets sensor data
and decides on actions.
Actuation Motors, hydraulic pistons, or solenoids convert commands into
physical movement.
Programmability Software (often stored as a sequence of instructions) defines the
robot’s tasks.
End‑effectors Specialized tools—grippers, spray guns, cutting blades—that
perform the final work.

Note – Not all “robots” possess artificial intelligence; many simply repeat programmed motions without adaptive decision‑making.

🤖 Physical vs. Software “Robots”


Physical robots have tangible hardware (sensors, actuators, processors).
Software robots (e.g., web crawlers, chatbots) simulate robotic behaviour in a purely digital environment and are not true
robots.

📡 Independent vs. Dependent Robots


Type Control relationship Example
Independent Operates autonomously with no human Autonomous vehicle, fully automated
input after start‑up. warehouse robot.
Dependent Requires direct human interfacing (e.g., a Tele‑operated assembly arm, collaborative
control panel). robot (cobot) that works alongside a
human.

🏭 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.

Advantages & disadvantages


Advantage Disadvantage
Operates continuously (24/7) without fatigue High capital cost; may increase unemployment for repetitive
tasks
Greater consistency and precision than humans Difficult to reprogram for non‑standard jobs
Can work in hazardous environments Requires regular maintenance and skilled technicians
Reduces long‑term labour costs Initial setup and integration can be complex

🚗 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.

Autonomous cars – key steps at a traffic light


1. Camera recognises the red signal.
2. Microprocessor matches the image to a traffic‑light database.
3. Brakes are applied and gear shifted to park.
4. System continuously monitors for obstacles (pedestrians, other vehicles).
5. When the light turns green, the processor releases brakes, engages first gear, and modulates the throttle.

Advantages & disadvantages


Vehicle type Advantages Disadvantages
Cars Reduced human error; potential lower Very high development cost; software
accident rates glitches can cause catastrophic failures
Trains Precise speed control; lower operating Expensive to retrofit existing rail
costs; fewer staff needed infrastructure; public acceptance can be
slow
Airplanes (pilot‑less) Improved passenger comfort; reduced Regulatory hurdles; reliance on flawless
crew costs; fewer pilot‑induced errors software; passenger reluctance without a
cockpit crew

🌾 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.

🏠 Domestic & Entertainment Robotics


Device Primary sensors/actuators Typical tasks
Autonomous vacuum Proximity sensors, LiDAR, brush motors Floor cleaning; obstacle avoidance
Personal assistant (e.g., Vector) Microphone, camera, speaker, wheels Voice‑controlled queries, face recognition,
navigation
Theme‑park animatronics Motion capture, servomotors, lighting rigs Interact with visitors, synchronise with
shows
Camera‑control rigs for film Gimbal motors, tracking software Keep shots steady, follow moving subjects
automatically
Robots in entertainment often combine precision (laser‑guided lighting) with creativity (synchronised choreography).

🧠 Artificial Intelligence in Automated Systems


Advantages
Stores and retrieves massive datasets, essential for research.
Learns patterns from data that would take humans months or years to discover.
Detects subtle correlations that might be missed by human analysts.

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.

🤖 Artificial Intelligence – Core Concepts


Artificial Intelligence (AI) – a collection of rules and data that gives a computer system the ability to reason, learn and adapt to
external stimuli.

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

Reasoning & Learning

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

📚 Machine Learning – From Data to Prediction


Machine learning (ML) – a sub‑field of AI in which algorithms are trained on historical data so they can make predictions or
decisions on unseen data without explicit programming.

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

🧩 Deep Learning – Neural Networks with Hidden Layers


Deep learning – a branch of ML that uses artificial neural networks composed of multiple hidden layers to model highly complex
relationships.

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.

Why Deep Learning Excels


Hierarchical feature learning: early layers detect edges; later layers combine edges into shapes, then into object concepts.
Scalability: performance improves as more training data and computational power become available.
Visual tasks: excels at image recognition (e.g., distinguishing bird species where traditional ML struggles).

Example: Image Classification


Each pixel’s RGB triplet is fed into the network.
After several hidden layers, the network outputs a probability distribution over possible objects (e.g., “sparrow = 0.82,
“finch = 0.11”).

📊 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

📸 Visual Aid – Mapping AI Components


The simplified transit map visualises how distinct AI components (expert‑system node, ML classifier, deep‑learning vision module) can
be linked together like stations on a network, enabling complex decision‑making pipelines.

🛠️ Practical Activities (Recap)


1. Identify AI terminology – match words such as knowledge base, inference engine, machine learning to their definitions.
2. Design an expert‑system dialogue – write a sequence of Yes/No questions that would lead to diagnosing mercury
poisoning from a set of symptoms.
3. Build a simple ML classifier – collect a small dataset of spam vs. ham emails, extract key words, and evaluate a naïve Bayes
model.
4. Experiment with a neural network – use a publicly available handwritten‑digit dataset (e.g., MNIST) to observe how adding
hidden layers improves accuracy.
These tasks reinforce the distinctions between rule‑based reasoning, statistical learning, and deep hierarchical models introduced
throughout the AI section.

🛠️ Algorithm Design Process


Algorithm design is the systematic approach to solving a problem by breaking it into manageable steps that a computer can execute.

The process consists of four linked stages:


1. Analysis – Identify the problem, its inputs, required processes, outputs and any storage needs.
2. Design – Create a high‑level blueprint using structure diagrams, flowcharts or pseudocode that shows how the sub‑tasks
interact.
3. Coding & Iterative Testing – Write each module in a programming language, test it, fix errors and repeat until the module
works correctly.
4. System Testing – Run the complete program with many different data sets to ensure all modules cooperate as specified.

As discussed earlier, the analysis stage clarifies what the program must achieve, while design focuses on how the tasks will be
organised.

🧩 Decomposition & Top‑Down Design


Decomposition (or stepwise refinement) is the technique of splitting a large problem into smaller sub‑systems until each
sub‑system performs a single, well‑defined action.

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.

Example: Alarm App on a Smartphone


Sub‑system Description
Set Alarm Select time, store it, handle snooze.
Check Time Continuously compare current clock with stored alarm time.
Ring Alarm Activate sound/vibration when times match.
The three high‑level modules can be further divided; for instance, Set Alarm may contain “Enter hour”, “Enter minute”, “Save”, and
“Enable snooze”.

This hierarchical breakdown lets several programmers develop different modules concurrently, reducing overall development time.

📊 Flowcharts and Pseudocode


Flowchart symbols (standard)
Symbol Meaning
Terminator (oval) Start / End of the algorithm
Process (rectangle) Action such as assigning a value
Input/Output (parallelogram) Read data from or write data to the user
Decision (diamond) Branching based on a condition (Yes/No)
Flow line (arrow) Direction of execution

Counting Passes – Flowchart


The diagram below shows a simple algorithm that counts how many students obtain a passing mark (> 50).

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.

Pseudocode conventions (IGCSE style)


Keywords such as INPUT, OUTPUT, IF, ENDIF, FOR, NEXT are written in CAPITALS.
Variables and sub‑routine names start with a capital letter.
Indentation (two spaces) indicates the body of loops or conditional blocks.
Assignment statement

Total ← Total + Mark

The variable on the left receives the value of the expression on the right.
Conditional statement (IF … THEN … ELSE)

IF Mark >= 50 THEN


Result ← "Pass"
ELSE
Result ← "Fail"
ENDIF

Multi‑way selection (CASE … OTHERWISE)

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.

📈 Standard Algorithmic Techniques


7.4.1 Totalling
Running total pattern: initialise a total to zero, then add each new value inside a loop.

7.4.2 Counting
Counting pattern: initialise a counter, increment each time a condition is met. The flowchart above illustrates this technique.

7.4.3 Maximum, Minimum & Average


1. Initialise Maximum and Minimum with the first list element.
2. Iterate through the remaining elements, updating Maximum if a larger value is found, and Minimum if a smaller value is
found.
3. Average = Total ÷ NumberOfItems.
7.4.4 Linear Search

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).

7.4.5 Bubble Sort

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.

🔐 Data Validation & Verification


Validation checks that entered data are reasonable before the system accepts them.
Verification confirms that the data have been recorded correctly (e.g., double entry).

Common validation checks


Check type Purpose Example
Range Value lies between lower and upper limits Marks must be 0 … 100
Length Exact or minimum/maximum number of Password must be exactly 8 characters
characters
Type Correct data type (integer, string, etc.) Number of siblings must be an integer
Presence Field is not left blank Email address is required
Format Matches a predefined pattern ISBN must be ISBN‑13 format
978‑0‑xxxx‑xxxx‑x
Check digit Detects transposition or missing digits ISBN check digit computed from the first
12 digits

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.

🧪 Testing with Test Data


Test data are the specific input values used to verify that an algorithm produces the expected results.

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).

Example: Average of ten marks


Test data (marks) Expected average
50, 50, 50, 50, 50, 50, 50, 50, 50, 50 50
0, 100, 50, 75, 25, 80, 20, 90, 10, 60 51
0, 0, 0, 0, 0, 0, 0, 0, 0, 0 0
Running the algorithm with each set confirms both the totalling and averaging logic.
When testing a full system, each sub‑module (e.g., Check Time in the alarm app) is exercised with its own test data before the whole
program is assembled and tested again.

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.

🧪 Types of Test Data


Test data are the specific input values used to exercise an algorithm and verify that it behaves correctly.

Category Purpose Typical Example (percentage Expected Outcome


marks)
Normal data Valid, everyday values that the 45, 78, 92 Accepted
program should accept
Abnormal / Erroneous data Values that violate the -12, 150 Rejected
problem’s constraints and must
be rejected
Extreme data Largest and smallest values 0, 100 Accepted
that are still within the allowed
range
Boundary data Values that sit exactly on the 99 (accepted), 101 (rejected) Accepted / Rejected
limit of acceptance; one side when the max is 100 accordingly
accepted, the other rejected
Activity 7.10 – Generate additional erroneous data for the “average percentage marks” algorithm and state the expected result
(rejection).
Activity 7.11 – Provide boundary data for the upper end of the range, assuming marks are whole numbers and the final exam is
un‑marked.

📋 Trace Tables & Dry‑Runs


Trace table – a structured table that records the value of each variable after every step of an algorithm during a dry‑run (manual
execution with test data).

How to construct a trace table


1. List variables as column headers.
2. Add an Output column to capture any values printed by the algorithm.
3. For each test datum, step through the algorithm, writing the new value of every variable after each operation.

Worked example (flowchart)


The flowchart below initializes A = 0, B = 0, C = 100, reads an input X , and then updates A, B , C based on comparisons withX .̀
The diagram shows the logical progression from start to stop, highlighting the decision points that decide whether X becomes the new
maximum ( ) or minimum ( ).
B C

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.

🐞 Identifying and Fixing Algorithm Errors


Error identification – By comparing the expected results (derived from the specification) with the actual results recorded in a trace
table, mismatches reveal logical mistakes.

Common error patterns observed in the max/min flowchart:


The initial provisional values for largest and smallest (A, B , C ) were set to 0, 0, 100. When all input numbers are negative,
the algorithm fails to recognise the true maximum because 0 (the initial largest) is larger than any negative input.
The smallest‑value check omitted the case where the first input is the smallest; consequently the smallest number 110 was
never identified in Activity 7.15.
Activity 7.15 – Using a trace table and a set of negative test data (e.g., -5, -20, -3), locate the error and propose a correction.
Improved algorithm – Initialise both provisional values to the first input rather than fixed constants. This ensures the algorithm works
for any numeric range.
Activity 7.16 – Determine a specific input set that still defeats the revised algorithm and explain why.
Activity 7.17 – Rewrite the pseudocode for the max/min problem using the “first‑item” initialisation technique, then test it with the
data 97, 12390, 77, 359, ‑85, 50, 21, 67.

🖥️ Designing Algorithms: From Problem to Pseudocode


Algorithm design – The systematic process of turning a problem description into a clear, executable set of steps.

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.

Example 2: School‑marks summary (pseudocode)

FOR each subject IN [Math, Science, English, IT] DO


INPUT mark
IF mark < 0 OR mark > 100 THEN
OUTPUT "Invalid mark"
CONTINUE
ENDIF
total[subject] ← total[subject] + mark
IF mark > high[subject] THEN high[subject] ← mark
IF mark < low[subject] THEN low[subject] ← mark
END FOR

FOR each subject DO


average[subject] ← total[subject] / number_of_students
OUTPUT subject, high[subject], low[subject], average[subject]
END FOR

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.

📐 Core Programming Concepts (Recap)


Variables store values that may change during execution; constants hold fixed values.

Concept Definition Example (pseudocode)


Variable Named storage whose value can be total ← 0
altered
Constant Named storage with an immutable value MAX_MARK ← 100
Input Prompting the user and reading a value INPUT mark
Output Displaying information to the user OUTPUT "Average:", avg
Selection Branching based on a condition (IF … IF mark ≥ 50 THEN PASS ← TRUE
THEN … ELSE)
Iteration Repeating a block (FOR, WHILE, REPEAT FOR i ← 1 TO n
… UNTIL)
Array Collection of same‑type elements indexed marks[1…n]
by position

Data types (relevant for test‑data validation)


INTEGER – whole numbers, used for counts, marks, IDs.
REAL – numbers with fractions, used for averages, measurements.
CHAR / STRING – single characters or text, used for names, passwords.
BOOLEAN – TRUE/FALSE, used for flags (e.g., valid ← FALSE).
Activity 8.2 – Declare the variables and constants needed to compute the volume of a cylinder in your chosen language (e.g., radius,
height, π).

✅ Validation & Verification Checklist


Validation ensures input data are reasonable before processing; verification confirms that processed data have been stored or
transmitted correctly.

Check type What it verifies Typical use in the “percentage‑marks”


context
Range check Value lies between lower and upper 0 ≤ mark ≤ 100
bounds
Length check Exact number of characters Password must be 8 characters
Type check Correct data type (integer, real) INTEGER for number of students
Presence check Field is not empty Name field must be filled
Format check Conforms to a pattern (e.g., email) xxx@[Link]
Check‑digit Detects transcription errors ISBN‑13 verification digit
When designing an algorithm, embed the appropriate checks before any calculations. Record the expected outcome for each test
datum (accept/reject) in a trace table.

🔧 Example: Parcel‑size Validation Algorithm


The flowchart (Figure 7.16) evaluates the dimensions of four parcels and decides whether each parcel is acceptable.
Step Action Validation rule
Input length, width, height Read three integers (cm) Each must be > 0
Compare to limits (e.g., length ≤ 150 cm) Decision node Range check on each dimension
If any dimension exceeds limit → reject Output “Parcel rejected” Record in trace table
Else → accept Output “Parcel accepted” Record in trace table
Activity 7.20 – Populate a trace table for the following parcel dimensions (cm): 15 × 10 × 20, 17 × 32 × 10, 30 × 35 × 30, 15 × 40 × 20,
12 × 10 × …. Identify any errors in the original flowchart logic.

📊 Extending to Abstract Data Types (ADTs)


Abstract Data Type – A logical description of a data structure together with the operations that can be performed on it,
independent of any specific implementation.

ADT Core principle Typical operations


Stack Last‑In‑First‑Out (LIFO) push(item), pop(), peek()
Queue First‑In‑First‑Out (FIFO) enqueue(item), dequeue(), front()
List Ordered collection add(index, item), remove(index),
get(index)
When an algorithm requires “store the numbers as they are read, then later retrieve the largest and smallest”, a stack could be used to
push each number and later pop them for analysis; a queue would preserve input order for a “first‑come‑first‑served” scenario.
📚 Key Terminology (Glossary)
Abnormal data – Input that violates the problem’s constraints and should be rejected.

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.

Verification – Confirmation that data have been accurately transferred or stored.

Decomposition – Breaking a complex problem into smaller, manageable sub‑problems.

Top‑down design – Starting with a high‑level description and iteratively refining into detailed steps.

Pseudocode – Language‑independent description of an algorithm using structured English‑like statements.

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

Example (find largest of three numbers)

IF a > b AND a > c THEN


largest ← a
ELSE IF b > c THEN
largest ← b
ELSE
largest ← c
ENDIF

📂 CASE (or SWITCH)


CASE selects one of many possible branches based on the value of an expression.

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

Example – counting marks (FOR)

DECLARE total, counter ← 0


FOR counter ← 1 TO 5 DO
INPUT mark
total ← total + mark
NEXT
average ← total / 5
OUTPUT "Average =", average

Example – sentinel‑controlled input (REPEAT…UNTIL)


DECLARE total, counter ← 0, mark
REPEAT
INPUT mark
IF mark = 999 THEN EXIT REPEAT
total ← total + mark
counter ← counter + 1
UNTIL FALSE
average ← total / counter
OUTPUT "Total =", total, "Average =", average, "Count =", counter

📊 Totalling & Counting


The following flowchart (image) shows a repeat‑until loop that gathers marks until the user enters 999.
The algorithm now starts the counter at ‑1 so the sentinel value is not counted, and the average is calculated after the loop finishes.

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.

➕ Arithmetic, Logical & Boolean Operators


Arithmetic Operators
Symbol Meaning Example
+ Addition a+b
- Subtraction a-b
* Multiplication a*b
/ Division (real result) a/b
DIV Integer division (quotient only) DIV(10, 3) → 3
MOD Modulus (remainder) MOD(10, 3) → 1
^ Exponentiation a^b

Logical (Comparison) Operators


Symbol Meaning
= Equal
<> Not equal
< Less than
> Greater than
<= Less than or equal
>= Greater than or equal

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

FOR student ← 1 TO classSize DO


FOR test ← 1 TO 5 DO
INPUT mark
UPDATE totals for this student
NEXT
CALCULATE studentAverage
NEXT

Example – selection inside a loop

REPEAT
INPUT mark
IF mark = 999 THEN EXIT REPEAT
IF mark >= 50 THEN
PASSCOUNT ← PASSCOUNT + 1
ELSE
FAILCOUNT ← FAILCOUNT + 1
ENDIF
UNTIL FALSE

🛠️ Procedures & Functions


Definitions

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 without parameters (pseudocode)

PROCEDURE DisplayStars
FOR i ← 1 TO 3 DO
OUTPUT "* * *"
NEXT
ENDPROCEDURE

CALL DisplayStars

Procedure with parameters

PROCEDURE PrintStars(count)
FOR i ← 1 TO count DO
OUTPUT "*"
NEXT
ENDPROCEDURE

CALL PrintStars(7) // prints seven asterisks

Function example – Fahrenheit to Celsius

FUNCTION ToCelsius(fTemp) RETURNS REAL


cTemp ← (fTemp - 32) * 5 / 9
RETURN cTemp
ENDFUNCTION

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

DECLARE scores[10] AS INTEGER // 10‑element integer array

The first index is typically 0 (Python, Java, C) unless the language specifies otherwise (Visual Basic starts at 0 as well).

Populating with a FOR loop

FOR i ← 0 TO 9 DO
INPUT scores[i]
NEXT

Accessing elements
Read: value ← scores[3] (fourth element)
Write: scores[7] ← 85

Two‑dimensional example (grades for 5 students, 3 tests)

DECLARE grades[5][3] AS INTEGER


FOR student ← 0 TO 4 DO
FOR test ← 0 TO 2 DO
INPUT grades[student][test]
NEXT
NEXT

Arrays enable compact storage, easy searching, and bulk operations such as calculating class averages.

🗂️ Writing Maintainable Code


Good practice Reason
Meaningful identifiers (e.g., totalMarks not t1) Improves readability for future developers
Consistent indentation Shows block structure, especially for nested loops/conditions
Comments using language‑specific syntax (# in Python, ' in Explain why a block exists, not just what it does
Visual Basic, // in Java)
Modularisation – split repetitive code into procedures/functions Reduces duplication and eases testing
Avoid magic numbers – store constants in clearly named Facilitates updates (e.g., MAX_MARK ← 100)
variables

📋 Activities (as listed in the transcript)


1. Activity 8.3 – Write and run a program that calculates and displays the volume of a cylinder.
2. Activity 8.4 – Using IF or CASE, write a program that selects data based on a criterion (e.g., largest value, items below a
price).
3. Activity 8.5 – Write a program that reads a number and checks whether it is ≥ 10.
4. Activity 8.6 – Create two short programs: one using a count‑controlled loop, the other a condition‑controlled loop; each
should iterate ten times, increment a counter, and output the counter value each iteration.
5. Activity 8.7 – Write a program that repeatedly reads the weight of rice sacks, counts how many sacks are entered, stops
when the user types a sentinel value, and then outputs the count and total weight.
6. Activity 8.8 – Input your full name, then:
Find and display the length of the name.
Extract the first three characters.
Show the name in UPPERCASE and lowercase.
7. Activity 8.9 – Write a short program that reads two numbers and displays the results of all basic arithmetic operations (+, -, *,
/, DIV, MOD).
8. Activity 8.10 – Write a program that compares three numbers and outputs messages identifying the largest, the smallest, and
whether any two are equal.
9. Activity 8.11 – Using nested loops, calculate and output the highest, lowest, and average marks for a single subject taken by
five students.
10. Activity 8.12 – Extend the previous program to handle six subjects per student.
11. Activity 8.13 – Further extend to process a whole class of 20 students (outer loop for students, inner loops for subjects and
tests).
12. Activity 8.14 – Define and use a procedure that displays three lines of asterisks; experiment with passing the number of
stars as a parameter.
13. Activity 8.15 – Extend the above to a procedure that prints a user‑specified number of stars.
14. Activity 8.16 – Write a function that converts a temperature from Fahrenheit to Celsius and returns the result; test it with
several inputs.
15. Activity 8.17 – Implement the algorithm from Activity 8.13 using procedures (local vs. global variables) to improve structure.
16. Activity 8.18 – List all variables, constants, and procedures used in Activity 8.13; identify which are global and which are
local.
17. Activity 8.19 – Identify the values returned by the library routines DIV, MOD, ROUND, and RANDOM for given sample
inputs.
18. Activity 8.20 – Write a short program that reads two numbers, computes a DIV b, and also generates a random integer
between 1 and 300.
19. Activity 8.21 – Exchange your last two programs with a peer; each must be able to understand and maintain the other’s
code.
20. Activity 8.22 – Declare a one‑dimensional array, populate it with ten integers using a loop, then output the value stored at
index 4.
21. Activity 8.23 – Declare and populate a two‑dimensional array representing grades for five students (three tests each); output
the grade for student 2, test 3.
These activities reinforce the concepts covered in this section and provide concrete practice with the high‑level language your school
uses.

📚 Two‑Dimensional Arrays – Tables of Data


Two‑dimensional array – a data structure that can be visualised as a table with rows and columns; each element is accessed by two
indexes (row, column).

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

DECLARE MyTable ARRAY[0..9, 0..2] OF INTEGER

The first index range (0 .. 9) defines 10 rows.


The second index range (0 .. 2) defines 3 columns.

Populating a 2‑D array


Two nested loops are required: an outer loop for rows, an inner loop for columns.

FOR rowCounter FROM 0 TO 9


FOR colCounter FROM 0 TO 2
OUTPUT "Enter value for row ", rowCounter, " column ", colCounter, ":"
INPUT MyTable[rowCounter, colCounter]
NEXT colCounter
NEXT rowCounter

Accessing a specific element

OUTPUT MyTable[2,1] // displays the value stored at row 2, column 1

If MyTable[2,1] contains 98, the program will print 98.

🐍 Python and Arrays – Lists & Nested Lists


List – the Python container that can hold elements of different data types; it replaces the classical fixed‑type array used in many
languages.

Language Array‑like structure Homogeneous? Example of 2‑D structure


Python list (nested lists) No – elements may differ my_table = [[27, 17, 48], [35,
29, 42]]
Java int[][] (array of arrays) Yes – same primitive type int[][] myTable = new int[10]
[3];
Visual Basic Integer(,) Yes – same type Dim myTable(9,2) As Integer
Key differences
Python lists can contain a mixture of numbers, strings, etc.; classic arrays (e.g., Java int[]) must hold only one primitive type.
Nested lists in Python are created by placing a list inside another list; the outer list’s length equals the number of rows, each
inner list’s length equals the number of columns.

📂 File Handling – Storing Data Permanently


File – a named collection of bytes stored on secondary storage; data written to a file persists after the program terminates, unlike
data kept only in RAM.

Why use files?


Preserve information across program runs.
Share data between different programs or computers.
Enable large‑scale data collection (e.g., logs, records).

Basic file operations (pseudocode)

DECLARE MyFile STRING "[Link]"

OPEN MyFile FOR WRITE


OUTPUT "Please enter a line of text:" TO MyFile
CLOSE MyFile

OPEN MyFile FOR READ


READ LINE FROM MyFile INTO textLine
OUTPUT textLine
CLOSE MyFile

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")

# read the line back


with open("[Link]", "r") as f:
textLine = [Link]()
print(textLine)

Visual Basic

Dim objMyFileWrite As Object


Set objMyFileWrite = CreateObject("[Link]")
Set objMyFileWrite = [Link]("[Link]", True)
[Link] "Please enter a line of text"
[Link]

Java
import [Link].*;

FileWriter fw = new FileWriter("[Link]");


BufferedWriter bw = new BufferedWriter(fw);
[Link]("Please enter a line of text");
[Link]();
[Link]();

FileReader fr = new FileReader("[Link]");


BufferedReader br = new BufferedReader(fr);
String textLine = [Link]();
[Link](textLine);
[Link]();

🏗️ Activities – Applying 2‑D Arrays & Files


Activity Goal Suggested Steps
8.23 Declare and populate the table shown in 1. Declare a 10 × 3 array.
Figure 8.11 (the MyTable example) using 2. Loop over rows (0‑9).
nested FOR loops in your chosen 3. Inside, loop over columns (0‑2).
language. 4. Prompt for each value and store it.
8.24 Write a program that writes a line to a file Follow the pseudocode above; translate
and then reads it back, using comments to to your language; add comments before
explain each step. each operation.
8.25 Copy text from one file to another; the 1. Open source file for reading.
algorithm must demonstrate sequence, 2. Open destination file for writing.
selection, iteration, totalling/counting, 3. While not EOF, read a line, optionally
string handling, nested statements, count characters, then write it.
operators, procedures/functions, and 4. Close both files.
library routines.
8.23 (Python) Use nested for loops to fill a Python list of my_table = [[0]*3 for _ in range(10)] then
lists that matches the table in Figure 8.11. nested loops to assign values.

📊 Databases – Single‑Table Foundations


Single‑table database – a database that contains exactly one table; every record (row) stores data about the same kind of entity.

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.

Example: PATIENT table


Field Data type Example value
HospitalNumber Short Text (primary key) HN123456
FirstName Short Text Winnie
FamilyName Short Text Sna
DateOfAdmission Date/Time 12/10/2022
Consultant Short Text Mr Smith
WardNumber Number (integer) 23
BedNumber Number (integer) 4
The primary key HospitalNumber guarantees each patient can be retrieved without ambiguity.

🛠️ Defining Fields & Validation in Access (or similar DBMS)


When creating a table, each field must be assigned a data type and optional validation rule.
WardNumber → Number; validation rule: >=1 AND <=10 (only whole numbers 1–10).
BedNumber → Number; validation rule: >=1 (positive integers).
Gender → Short Text; validation rule: In ("Male","Female","Other").
These rules prevent illegal entries such as a negative ward number or a miss‑spelled gender.

📑 SQL Basics – Querying a Single‑Table Database


SQL (Structured Query Language) – the standard language for defining, manipulating, and retrieving data from relational
databases.

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 HospitalNumber, FirstName, FamilyName


FROM PATIENT
WHERE Consultant = 'Mr Smith';
2. All patients ordered alphabetically by family name

SELECT HospitalNumber, FirstName, FamilyName


FROM PATIENT
ORDER BY FamilyName ASC;

3. Count patients admitted between two dates

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.

🧩 Extending to A‑Level Concepts (brief overview)


DDL (Data Definition Language) – SQL commands that create, alter, or drop database structures (e.g., CREATE TABLE).

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.

📂 SQL Data Definition Language (DDL) – Setting Up a Database


DDL commands define the structure of a database. They are executed once (or when the schema changes) and do not manipulate
the data itself.

Command Purpose Example


CREATE DATABASE Creates a new database container CREATE DATABASE CubScout;
CREATE TABLE Defines a table’s columns, data types and CREATE TABLE CUB ( … );
constraints
ALTER TABLE Modifies an existing table definition (add ALTER TABLE CUB ADD PRIMARY KEY
columns, change types, etc.) (CubNumber);
PRIMARY KEY Declares a column (or set of columns) that PRIMARY KEY (CubNumber)
uniquely identifies each record
These commands were introduced after the discussion of single‑table databases in the previous chapter.

📊 Data Types for Table Attributes


Data types constrain the kind of information that can be stored in a field, helping to enforce validity and optimise storage.

SQL Type Description Typical Use


CHAR(n) Fixed‑length text, exactly n characters Country codes, status flags
(padded with spaces)
VARCHAR(n) Variable‑length text, up to n characters Names, addresses
BOOLEAN Logical true/false, stored as 1 (true) or 0 Active flag, “IsMember”
(false)
INTEGER Whole numbers (no decimal) IDs, counts
REAL Floating‑point numbers with fractional Prices, measurements
part
DATE Calendar date, format YYYY‑MM‑DD Birthdate, order date
TIME Clock time, format HH:MM:SS Appointment time, log timestamp
When designing a table, choose the narrowest type that still accommodates the expected values – a principle echoed from the earlier
discussion on binary storage efficiency.

🛠️ Example: Creating the CubScout Database


CREATE DATABASE CubScout;

CREATE TABLE CUB (


CubNumber INTEGER, -- will become the primary key
CubName VARCHAR(30),
DateOfBirth DATE,
Address VARCHAR(40),
Gender CHAR(1), -- ‘M’ or ‘F’
School VARCHAR(30),
TelephoneNumber CHAR(14),
DateJoined DATE
);

ALTER TABLE CUB ADD PRIMARY KEY (CubNumber);

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.

🔑 Primary Keys and Table Design


A primary key is a column (or combination) whose values are unique and non‑null for every record.

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.

📑 Querying Single‑Table Databases (SQL DML)


Data Manipulation Language (DML) commands operate on the data stored in tables.

Command Syntax Sketch Typical Use


SELECT SELECT column1, column2 FROM table; Retrieve specific fields
WHERE SELECT * FROM table WHERE condition; Filter rows
COUNT SELECT COUNT(*) FROM table; Number of rows
SUM SELECT SUM(column) FROM table; Aggregate numeric totals
ORDER BY SELECT … FROM table ORDER BY column Sort results
ASC;
GROUP BY (not covered yet) … Summarise by categories
These commands complement the CREATE statements introduced earlier and were referenced when explaining how to extract data
from the PATIENT and CAR examples.

🗂️ Exam‑Style Database Questions


1. CAR table – Determine the number of records and fields, justify a primary‑key choice, and write a query to list all cars with
leather seats and silver or grey paint:

SELECT * FROM CAR


WHERE SeatMaterial = 'Leather' AND PaintColour IN ('Silver','Grey');

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.

🧩 Logic Gates & Boolean Algebra


Logic gates are the physical building blocks of digital circuits; each implements a Boolean function.

Gate Symbol Boolean Expression Truth Table (A, B → X)


NOT !A X = ¬A 0→1, 1→0
AND A ∧ B X = A ∧ B 0 0→0, 0 1→0, 1 0→0, 1 1→1
OR A ∨ B X = A ∨ B 0 0→0, 0 1→1, 1 0→1, 1 1→1
NAND A ∧ B X = ¬(A ∧ B) 0 0→1, 0 1→1, 1 0→1, 1 1→0
NOR A ∨ B X = ¬(A ∨ B) 0 0→1, 0 1→0, 1 0→0, 1 1→0
XOR A ⊕ B X = (A ∧ ¬B) ∨ (¬A ∧ B) 0 0→0, 0 1→1, 1 0→1, 1 1→0
Images of the NOT and AND gates (including truth tables) are shown below.

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.

📈 Truth Tables and Logic Expressions


A truth table enumerates every possible combination of input values and the corresponding output of a logic circuit.

Constructing a truth table


1. List all 2 input combinations for n inputs.
n

2. Evaluate the Boolean expression step‑by‑step (intermediate results may be recorded).


3. Record the final output column.
Example: For the expression (A ∧ B) ⊕ (B ∨ C ) , the truth table (shown in the lecture image) has eight rows because there are three
inputs.
The diagram shows three inputs (A, B, C) feeding into an AND gate and an OR gate; their outputs are combined by an XOR gate to
produce X.

Activity 10.1 asked students to prove that


X = A ∧ ¬B ∨ (¬A ∧ B)

and
X = (¬A ∧ B) ∨ (A ∧ ¬B)

represent the same logic function—both are algebraic rearrangements of the XOR truth table.

🔀 Building Logic Circuits


The lecture presented a systematic method for translating a Boolean expression into a physical circuit:
1. Identify basic sub‑expressions (e.g., A ∧ B , B ∨ C ).
2. Assign a gate to each sub‑expression.
3. Connect gate outputs to subsequent gates according to the expression hierarchy.
4. Optionally label intermediate nodes (P, Q, R) to aid debugging (as shown in Figure 10.3).
Example: The expression ((A ∧ B) NAND (A ∨ ¬B)) is implemented by first wiring an AND gate and an OR‑NOT pair, then feeding
both into a NAND gate.
The step‑wise approach mirrors the earlier algorithm design workflow (analysis → decomposition → implementation → testing).

➕ Half‑Adder and Full‑Adder Circuits


Adders are fundamental combinational circuits that perform binary addition.

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

Extends the half‑adder to include a third input C (carry‑in).


in ​

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.

🔧 Full‑Adder and Multi‑Bit Addition


Full‑adder – a combinational circuit that adds three binary bits: two operand bits (A, B) and a carry‑in (Cᵢₙ). It produces a sum bit (S)
and a carry‑out (Cₒᵤₜ).

Half‑adder adds only A and B (no carry‑in).


The full‑adder is the basic building block for adding numbers wider than one bit.
Full‑adder implementation
Gate used Purpose
XOR Produces the sum (A ⊕ B ⊕ Cᵢₙ)
AND Generates the two intermediate carries (A ∧ B) and (B ∧ Cᵢₙ)
OR Combines the intermediate carries to give carry‑out (
(A ∧ B) ∨ (B ∧ Cᵢₙ) ∨ (A ∧ Cᵢₙ) )
Four‑bit addition example – Adding two 4‑bit numbers requires four cascaded full‑adders. The carry‑out of each stage feeds the
carry‑in of the next more‑significant stage, exactly as described earlier for binary addition (see the Binary Arithmetic section).

📊 Logic‑Gate Symbols Review


Gate Symbol (text) Boolean expression
NOT !A ¬A

AND A∧B A ∧ B

OR A∨B A ∨ B

NAND A↑B ¬(A ∧ B)

NOR A↓B ¬(A ∨ B)

XOR A⊕B (A ∧ ¬B) ∨ (¬A ∧ B)

These symbols were introduced earlier; you should recognise them when constructing truth tables or drawing circuits.

🧩 From Boolean Expression → Truth Table → Logic Circuit


Step 1 – Write the Boolean expression.
Example: ; ¬A ∧ B; ∨; A ∧ ¬B
Step 2 – Build the truth table.
A B ¬A ¬B ¬A ∧ B A ∧ ¬B Output (X)
0 0 1 1 0 0 0
0 1 1 0 1 0 1
1 0 0 1 0 1 1
1 1 0 0 0 0 0
Step 3 – Draw the circuit.
Use a NOT gate for each negated input.
Feed the results into two AND gates (the two middle columns).
Combine the two AND outputs with an OR gate to produce X.
The diagram mirrors Figure 10.42 in the transcript, where four half‑adder circuits were combined to form a full adder; the same
systematic approach applies here.

📈 Completing Truth Tables


When a problem provides only a partial table, fill in the missing rows by evaluating the Boolean expression for every possible input
combination (2ⁿ rows for n inputs).
Example fragment (from the transcript)
Input A Input B Output X
0 1 1
1 0 1
… … …
Complete the table by adding the two missing rows (0 0 and 1 1) and evaluating the expression shown above, yielding 0 for both.

⚙️ Safety‑System Example – Motor & Pump


Monitored parameters (binary inputs)
Parameter Binary value Condition description
Motor speed (rpm) M M = 1 ⇔ speed = 2000 rpm

Bearing temperature (°C) T T = 1 ⇔ temperature = 90 °C

Water velocity (m/s) V V = 1 ⇔ velocity = 1 m/s

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 .

🏭 Manufacturing Alarm for Plastic‑Pipe Production


Inputs (binary)
Input Binary value Physical condition
Pressure P 1 P > 10 bar
Temperature T 1 T > 150

C
Production speed S 1 S > 2 m/s
Alarm requirement – Sound alarm X when temperature > 200 °C and either (pressure > 10 bar or speed > 2 m/s).
Boolean expression (max two inputs per gate)
1. First create P ∨ S using an OR gate.
2. Then AND that result with T (temperature > 200 °C).
200 ​

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 )

Truth table (showing only relevant rows)

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 ​

Benefits of using sensors in this line


Benefit Explanation
Real‑time monitoring Detects out‑of‑range pressure or temperature instantly, enabling
immediate shutdown.
Reduced waste Prevents production of defective pipes caused by overheating or
over‑pressurisation.
Safety compliance Automatic alarms satisfy industry safety standards without
relying on manual observation.

📹 DVD‑Recorder Warning System (Three Sensors)


Inputs
Input Binary value Condition
Rotation speed R 1 R = 1000 rpm
Tilt angle A 1 A = 150

Laser power L 1 L = 150 mW


Warning output – Display warning if any of the following combinations occur:
1. R = 1 and A = 1
2. R = 1 and L = 1
3. A = 1 and L = 1
Boolean expression
W = (R ∧ A); ∨; (R ∧ L); ∨; (A ∧ L)

Truth table (selected rows)


R A L R ∧ A R ∧ L A ∧ L W
0 0 0 0 0 0 0
0 1 1 0 0 1 1
1 0 1 0 1 0 1
1 1 0 1 0 0 1
1 1 1 1 1 1 1
Circuit – Three two‑input AND gates generate the pairwise products; their outputs feed a two‑stage OR network (first OR combines
two products, second OR adds the third).

📑 Exam‑Style Tasks (from the transcript)


1. Derive the Boolean expression for a given truth table (table not reproduced here).
2. Draw the corresponding logic circuit for the expression ¬A ∧ B; ∨; A ∧ ¬B .
3. Complete the truth table for a provided circuit (e.g., the motor‑speed safety circuit).
4. Write the logic expression for the plastic‑pipe alarm scenario, ensuring each gate has at most two inputs.
5. Identify the single gate that matches a given input‑output mapping (e.g., a truth table with one‑output column).
These items directly assess the ability to move between Boolean expressions, truth tables, and gate‑level implementations – skills
reinforced throughout the chapter.

📚 Key Terms (throughout this chapter)


Full‑adder – circuit that adds three binary bits (A, B, Cᵢₙ) producing a sum and a carry‑out.

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.

You might also like