Understand and use nested selection and iteration statements

Nested Selection & Iteration – Cambridge IGCSE 0478 (2026‑2028)

1. Algorithmic Foundations (Syllabus Topics 7‑10)

1.1 The Algorithm Design Life‑Cycle

  1. Analyse – understand the problem, identify required data and constraints.
  2. Design – decompose the problem, choose suitable algorithmic methods (search, sort, totalling, etc.) and decide on a flow‑chart or pseudocode structure.
  3. Code – translate the design into correct pseudocode (or a programming language) using Cambridge conventions.
  4. Test – use trace tables, validation checks and sample data to verify the solution.
  5. Evaluate – comment on correctness, efficiency (time‑complexity) and possible improvements.

1.2 Decomposition Example

Problem: “Find the highest mark in a class and list all students who achieved it”.

  1. Read the number of students.
  2. Loop to read each mark (store in an array).
  3. Find the maximum value (single pass).
  4. Loop again to output the names whose mark = maximum.

1.3 Pseudocode Conventions (Cambridge style)

ElementCambridge convention
KeywordsUPPERCASE (IF, ELSE, FOR, WHILE, END IF, END FOR, BREAK, CONTINUE)
IdentifiersPascalCase or lower_case (e.g., totalScore)
CommentsEnclosed in // or placed on a separate line beginning with #
Indentation4 spaces per nesting level (prevents “dangling‑else” errors)
OperatorsArithmetic (+, –, *, /, MOD), relational (=, ≠, <, >, ≤, ≥), logical (AND, OR, NOT)

1.4 Boolean Logic & Logic‑Gate Symbols

OperatorExpressionGate Symbol
ANDA AND B& (⋀)
ORA OR B≥ (⋁)
NOTNOT A¬

2. Data Representation (Syllabus 1)

2.1 Number Systems & Two’s‑Complement

DenaryBinary (8‑bit)Hexadecimal
00000 000000
130000 11010D
2551111 1111FF
-11111 1111FF
-1281000 000080

Overflow example: Adding 120 (0111 1000) and 20 (0001 0100) gives 1000 1100, which as an 8‑bit two’s‑complement value represents –124. The result is an overflow error.

2.2 Logical Shift Operations

Given 10110100₂:

  • Logical left shift << 2 → 11010000₂ (binary 208)
  • Logical right shift >> 3 → 00010110₂ (binary 22)

2.3 Text, Sound & Images (Syllabus 1.2)

AspectKey Details
ASCII7‑bit, 128 characters, e.g., ‘A’ = 65 (0100 0001₂)
Unicode (UTF‑8)Variable‑length, covers world scripts; ‘Ω’ = 937 (CE B3 in hex)
Sample rateSamples per second (e.g., 44 kHz = 44 000 samples s⁻¹)
Resolution (image)Pixels in width × height (e.g., 1920 × 1080)
Colour depthBits per pixel – 24‑bit = 16 777 216 colours

File‑size example (audio): 44 kHz, 16‑bit mono, 5 s → 44 000 × 16 × 5 ÷ 8 = 440 000 bytes ≈ 429 KiB.

2.4 Data Storage & Compression (Syllabus 1.3)

UnitValue (bytes)
1 KiB2¹⁰ = 1 024 B
1 MiB2²⁰ = 1 048 576 B
1 GiB2³⁰ = 1 073 741 824 B
1 TiB2⁴⁰ = 1 099 511 627 776 B

Image size calculation: 800 × 600 px, 24‑bit colour → 800 × 600 × 24 ÷ 8 = 1 440 000 B ≈ 1 406 KiB.

Run‑Length Encoding (RLE) example: 11110000(4,1)(4,0) (four 1s, four 0s) – a simple loss‑less compression.

3. Data Transmission (Syllabus 2)

3.1 Packet Structure

ComponentPurpose
HeaderSource/destination address, protocol type, length
PayloadActual data being transmitted
TrailerError‑detection bits (e.g., CRC, checksum)

3.2 Error Detection & Correction

  • Parity bit – even or odd parity; detects a single‑bit error.
  • Checksum – sum of all bytes modulo 256; simple but limited.
  • CRC (Cyclic Redundancy Check) – polynomial division; widely used in Ethernet.
  • ARQ (Automatic Repeat Request) – sender retransmits if receiver signals error.

3.3 Switching & USB

  • Circuit switching – dedicated path for the duration of a call.
  • Packet switching – data broken into packets, each routed independently.
  • USB 2.0 – 480 Mbps, half‑duplex, supports hot‑plugging and power delivery.

3.4 Encryption (Symmetric vs Asymmetric)

TypeKey(s)Typical Use
SymmetricSingle secret key (same for encrypt & decrypt)Bulk data encryption (e.g., AES)
AsymmetricPublic key + private key pairSecure key exchange, digital signatures (e.g., RSA)

4. Hardware (Syllabus 3)

4.1 CPU & Von Neumann Architecture

  • ALU – performs arithmetic and logical operations.
  • CU (Control Unit) – fetches, decodes and controls execution of instructions.
  • Registers – small, fast storage inside the CPU (e.g., ACC, PC).
  • Bus system – data, address and control buses connect CPU, memory and I/O.

4.2 Fetch‑Decode‑Execute Cycle (FDE)

  1. Fetch – read the next instruction from memory (address held in PC).
  2. Decode – CU interprets opcode and determines required operands.
  3. Execute – ALU performs operation; result may be stored or sent to I/O.

4.3 Cores, Cache & Instruction Sets

  • Multi‑core – two or more processing units on a single chip; enables parallel execution.
  • Cache hierarchy – L1 (fastest, smallest), L2, L3; reduces average memory access time.
  • Instruction set – RISC (fixed‑length, simple) vs. CISC (variable‑length, complex).

4.4 Embedded Systems (real‑world example)

Arduino‑based thermostat:

  • Microcontroller (CPU + RAM + Flash) reads a temperature sensor.
  • Runs a simple loop (nested selection to decide heating/cooling).
  • Outputs to a relay (actuator) and displays status on an LCD.

4.5 I/O Devices & Sensors (Syllabus 3.2)

DeviceCategoryTypical Data Type
KeyboardInputText / character codes
MouseInputNumeric (x, y coordinates)
TouchscreenInput/OutputNumeric (coordinates) + Text
Temperature sensorInputNumeric (°C or °F)
AccelerometerInputNumeric (g‑force on three axes)
SpeakerOutputSound wave (digital samples)
LED arrayOutputBinary (on/off) or colour values

4.6 Data Storage (Syllabus 3.3)

Storage TypeTypical MediumAdvantagesDisadvantages
Primary (RAM)Volatile semiconductorFast access, random‑accessLost when power removed
Secondary – MagneticHDDLarge capacity, cheap per GBMechanical wear, slower
Secondary – OpticalCD/DVD/BlurayPortable, read‑only (archival)Limited rewrite cycles
Secondary – SSDFlash memoryNo moving parts, fast random accessHigher cost per GB
Virtual memoryHard‑disk paging fileExtends usable RAMSlower than physical RAM
Cloud storageRemote servers via InternetAccess from anywhere, redundancyDepends on network, security concerns

4.7 Network Hardware (Syllabus 3.4)

ComponentFunction
NIC (Network Interface Card)Provides MAC address, handles physical‑layer signalling
SwitchConnects devices within a LAN, forwards frames based on MAC
RouterRoutes packets between different networks, uses IP addresses
FirewallFilters traffic according to security rules (packet‑filter or stateful)
Wireless Access Point (WAP)Provides Wi‑Fi connectivity, bridges wired and wireless segments

5. Selection & Iteration – Core Concepts

5.1 Selection (IF‑ELSE, CASE)

  • Chooses one of several possible execution paths.
  • Cambridge permits CASE … OF … END CASE (often called SWITCH).

5.2 Iteration (FOR, WHILE, DO‑WHILE)

  • Repeats a block of statements a known or unknown number of times.
  • Use BREAK to exit early, CONTINUE to skip to the next iteration.

5.3 Flow‑chart Symbols

  • Oval – Start / End.
  • Parallelogram – Input / Output.
  • Rectangle – Process (assignment, calculation).
  • Diamond – Decision (selection).
  • Connector (small circle) – Links flow‑lines to avoid crossing.

6. Nested Selection

6.1 Definition

A selection statement placed inside another selection (or inside a loop). The inner IF is evaluated only when the outer condition is true.

6.2 Example – Letter Grade (nested IF)

INPUT mark
IF mark >= 0 AND mark <= 100 THEN
    IF mark >= 80 THEN
        SET grade = "A"
    ELSE IF mark >= 70 THEN
        SET grade = "B"
    ELSE IF mark >= 60 THEN
        SET grade = "C"
    ELSE IF mark >= 50 THEN
        SET grade = "D"
    ELSE
        SET grade = "F"
    END IF
    PRINT "Grade:", grade
ELSE
    PRINT "Invalid mark – must be 0‑100"
END IF

6.3 Example – Letter Grade using CASE

INPUT mark
IF mark < 0 OR mark > 100 THEN
    PRINT "Invalid mark"
ELSE
    CASE mark DIV 10 OF
        10, 9, 8: SET grade = "A"
        7:       SET grade = "B"
        6:       SET grade = "C"
        5:       SET grade = "D"
        0 TO 4: SET grade = "F"
    END CASE
    PRINT "Grade:", grade
END IF

7. Nested Iteration

7.1 Definition

A loop placed inside another loop. The inner loop runs **completely** for each iteration of the outer loop.

7.2 Time‑Complexity Tip (AO3)

If the outer loop executes m times and the inner loop executes n times, total iterations = m × n → O(m·n).

7.3 Example – Multiplication Table (1‑10)

FOR i = 1 TO 10 DO
    FOR j = 1 TO 10 DO
        SET product = i * j
        PRINT i, "×", j, "=", product
    END FOR
END FOR

7.4 Example – 2‑D Array Traversal

FOR row = 1 TO rows DO
    FOR col = 1 TO cols DO
        PRINT array[row][col], " "
    END FOR
    PRINT NEWLINE
END FOR

8. Combined Nested Selection‑Iteration

8.1 Typical Pattern

Iterate over a data set, then decide what to do with each element.

8.2 Example – Even Numbers between 1 and 50

FOR n = 1 TO 50 DO
    IF n MOD 2 = 0 THEN
        PRINT n, "is even"
    END IF
END FOR

9. Core Algorithmic Methods (Syllabus 7‑10)

MethodPurposeTypical Pseudocode (Cambridge style)
Linear Search Find the first occurrence of a target value in a list/array.
INPUT target
SET position = -1
FOR i = 1 TO LENGTH(array) DO
    IF array[i] = target THEN
        SET position = i
        BREAK
    END IF
END FOR
IF position = -1 THEN
    PRINT "Not found"
ELSE
    PRINT "Found at position", position
END IF
Bubble Sort Sort a numeric array in ascending order using repeated swaps.
FOR pass = 1 TO LENGTH(array)-1 DO
    FOR i = 1 TO LENGTH(array)-pass DO
        IF array[i] > array[i+1] THEN
            SET temp = array[i]
            SET array[i] = array[i+1]
            SET array[i+1] = temp
        END IF
    END FOR
END FOR
Totalling / Counting Calculate sum, count, average, maximum, minimum.
SET total = 0
SET count = 0
SET max = -∞
SET min = +∞
FOR i = 1 TO LENGTH(data) DO
    SET value = data[i]
    SET total = total + value
    SET count = count + 1
    IF value > max THEN SET max = value END IF
    IF value < min THEN SET min = value END IF
END FOR
SET average = total / count
PRINT "Sum:", total, "Average:", average
PRINT "Max:", max, "Min:", min

9.1 Trace Table – Bubble Sort (first two passes, 5‑element list)

PassiArray after inner loop
11‑43  2  5  1  4
21‑32  1  3  4  5

10. Validation & Verification

10.1 Validation (checking user input before use)

  • Type check – ensure data is numeric, text, etc.
  • Range check – e.g., IF age < 0 OR age > 120 THEN …
  • Length check – for strings, e.g., password must be ≥ 8 characters.

10.2 Verification (checking that the algorithm works as intended)

Use a trace table with at least three test cases: normal, boundary, and error case.

10.3 Example – Validating a Score (0‑100)

INPUT score
IF IS_NUMERIC(score) = FALSE THEN
    PRINT "Error – not a number"
ELSE IF score < 0 OR score > 100 THEN
    PRINT "Error – out of range"
ELSE
    PRINT "Score accepted:", score
END IF

11. Worked Example – Prime‑Number Test (Improved)

11.1 Pseudocode (Cambridge style)

INPUT n
IF n < 2 THEN
    PRINT n, "is NOT a prime number"
    STOP
END IF
SET isPrime = TRUE
FOR i = 2 TO FLOOR(SQRT(n)) DO
    IF MOD(n, i) = 0 THEN
        SET isPrime = FALSE
        BREAK
    END IF
END FOR
IF isPrime = TRUE THEN
    PRINT n, "is a prime number"
ELSE
    PRINT n, "is NOT a prime number"
END IF

11.2 Trace Table (n = 29)

iMOD(29,i)isPrime
21TRUE
32TRUE
41TRUE
54TRUE

The loop stops after i = 5 because FLOOR(√29) = 5. No divisor found → isPrime = TRUE.

11.3 Efficiency Note (AO3)

Testing divisors only up to √n reduces the number of iterations from O(n) to O(√n), a noticeable improvement for large n.

11.4 Flow‑chart (text description)

  1. Start
  2. Input n
  3. Decision: n < 2? – Yes → “not prime”, End; No → continue.
  4. Set isPrime ← TRUE
  5. FOR i ← 2 TO √n
    • Decision: MOD(n,i)=0?
      • Yes → isPrime ← FALSE, BREAK
      • No → continue loop
  6. Decision: isPrime?
    • Yes → output “prime”
    • No → output “not prime”
  7. End

12. Practice Exercises (with brief guidance)

  1. Multiplication Table (1‑10) – Use a nested FOR loop. Format output in a grid (e.g., tab‑separated).
  2. Letter Grade (CASE version) – Rewrite the nested‑selection example using CASE … OF … END CASE. Remember to validate the input first.
  3. Even Numbers 1‑50 – Combine a FOR loop with an IF that uses MOD. Add a CONTINUE to skip odd numbers if you wish.
  4. Spot‑the‑Error – Identify and correct the mistake:
    FOR i = 1 TO 10 DO
        FOR j = 1 TO 10 DO
            j = j + 1      // error
        END FOR
    END FOR
    
    Hint: The inner‑loop variable must not be altered inside the loop body; remove the assignment or replace it with CONTINUE if the intention was to skip an iteration.
  5. Linear Search Trace Table – Use the data set {7, 3, 9, 5} and target 9. Show the values of i, position and any BREAK occurrence.
  6. File‑Handling (optional) – Write pseudocode to read a text file of student scores, validate each score (0‑100), store valid scores in an array, and output the class average.
  7. RLE Compression – Given the binary string 111100001111, write pseudocode that produces the RLE pairs and show the resulting list.
  8. Network Packet Checksum – Write a short algorithm that adds all bytes of a packet (mod 256) and appends the checksum; then verify with a sample packet.

13. Quick Revision Checklist

  • Can you convert between binary, denary and hexadecimal, and explain two’s‑complement overflow?
  • Do you know the difference between ASCII and Unicode and can you calculate simple file sizes for audio, images and text?
  • Are you able to draw a packet diagram and explain parity, checksum and CRC?
  • Can you label the main parts of a CPU and describe the FDE cycle?
  • Do you recognise common sensors/actuators and the data type they produce?
  • Can you compare magnetic, optical and SSD storage, and discuss cloud vs. local storage?
  • Are you comfortable writing nested selection and nested iteration pseudocode, tracing them, and analysing their time‑complexity?
  • Can you apply validation (type, range, length) and verification (trace tables) to any algorithm?

Create an account or Login to take a Quiz

39 views
0 improvement suggestions

Log in to suggest improvements to this note.