Understand and use nested statements

Programming – Understanding and Using Nested Statements (IGCSE 0478)

1. The Algorithm Development Cycle

  • Analysis & decomposition – break the problem into smaller sub‑problems; each sub‑problem often becomes a nested control structure.
  • Design (pseudocode / flowchart) – show hierarchy with indentation (pseudocode) or branches (flowchart).
  • Implementation (coding) – translate the nested design into a programming language.
  • Testing & verification – use trace tables to follow the flow through every level of nesting.

Trace‑table example (nested if)

Step Score Outer if (0 ≤ Score ≤ 100) Inner if (Score ≥ 70?) Grade
185TrueTrueA
262TrueFalseB
338TrueFalseF
4‑5FalseInvalid mark

2. Cambridge IGCSE Computer Science – Syllabus Overview

2.1 Computer Systems (Topics 1‑6)

TopicKey Points to Cover
1. Data Representation
  • Binary, denary, hexadecimal conversion.
  • Two’s‑complement for signed integers.
  • Bitwise operators, logical shifts, overflow.
  • Character encoding (ASCII, Unicode).
2. Data Transmission
  • Packet structure – header, payload, trailer.
  • Packet switching vs. circuit switching.
  • Common interfaces: USB, Ethernet, Wi‑Fi.
  • Error‑detection: parity bit, checksum, CRC.
  • Basic encryption concepts – symmetric vs. asymmetric.
3. Hardware
  • Von Neumann architecture – CPU, memory, I/O.
  • Fetch‑Decode‑Execute cycle.
  • CPU components: ALU, registers, control unit.
  • Clock speed, cores, cache hierarchy.
  • Embedded systems – examples and constraints.
4. Software
  • System software vs. application software.
  • Operating‑system functions: resource management, file‑system, multitasking, security.
  • Interrupts – hardware and software.
  • Programming‑language levels – machine, assembly, high‑level.
  • Integrated Development Environments (IDEs) and debugging tools.
5. Data Management
  • Database concepts – tables, records, fields, primary key.
  • Simple SQL: SELECT, WHERE, INSERT, UPDATE, DELETE.
  • Data validation and integrity constraints.
6. Ethical, Legal & Environmental Issues
  • Data protection, privacy, intellectual property.
  • Impact of computing on society and the environment.

2.2 Algorithms – Programming & Logic (Topics 7‑10)

The remainder of these notes focuses on the programming side, especially nested statements, which are central to Topics 8 (Programming) and 9 (Databases).

3. Core Programming Concepts (Topic 8)

ConceptWhat you need to knowExample (Python)
Variables & data types INTEGER, REAL, BOOLEAN, STRING, LIST/ARRAY score = 0 # int
name = "Alice" # str
Input / output INPUT / OUTPUT (or print) score = int(input("Enter mark: "))
print("Grade:", grade)
Operators Arithmetic (+, –, *, /, //, %), Relational (=, ≠, <, >, ≤, ≥), Logical (and, or, not) if score >= 70 and score <= 100:
Selection (if‑else) Single, chained, and nested if See Section 4
Iteration (loops) while, for (count‑controlled and collection‑controlled) for i in range(1, 11):
  print(i)
String handling Concatenation (+), slicing, length, conversion msg = "Score: " + str(score)
Procedures / functions Define once, call many times; may return a value def grade_mark(m):
  if m >= 70: return "A"
  ...
  return "F"
Libraries / modules Import standard or user‑defined modules (e.g., import math) import random
dice = random.randint(1,6)

4. Nested Statements – Definition, Syntax & Patterns

4.1 What is a Nested Statement?

  • A control structure placed inside another control structure.
  • The inner block is executed only when the outer condition (or loop entry) is satisfied.
  • Used to model real‑world hierarchies, avoid duplicated code, and keep algorithms readable.

4.2 Common Nesting Patterns

Outer structureTypical inner structuresTypical use
if … else if … else inside either branch Multi‑level decision making
while loop if … else or another while Repeated checks while a condition holds
for loop if … else or another for Iterating over a collection with extra criteria

4.3 Syntax (Python, Java, Pseudocode)

# Python – indentation defines the block
if condition1:
    # outer block
    if condition2:
        # inner block
        statement
    else:
        # inner else
        statement
else:
    # outer else
    statement
// Java – braces define the block
if (condition1) {
    if (condition2) {
        // inner block
        statement;
    } else {
        // inner else
        statement;
    }
} else {
    // outer else
    statement;
}
# Pseudocode (Cambridge style)
IF condition1 THEN
    IF condition2 THEN
        statement
    ELSE
        statement
    ENDIF
ELSE
    statement
ENDIF

4.4 Boolean Logic Refresher (Topic 10)

  • Logical operators: AND (·), OR (+), NOT (‾).
  • Truth tables are essential for verifying nested if conditions.
  • Nested tests can be expressed as a single Boolean expression using and/or, but the nested form is often clearer for beginners.
Truth table for a two‑level nested test
C₁C₂C₁ AND C₂
000
010
100
111

5. Arrays & Nested Loops

5.1 One‑Dimensional Arrays

Store a collection of values of the same type. Indexing starts at 0 in most languages (Python, Java, C#).

# Python – find the highest mark
marks = [78, 92, 65, 88, 73]

max_mark = marks[0]                     # initialise with first element
for i in range(1, len(marks)):          # outer FOR over indices
    if marks[i] > max_mark:             # nested IF inside the FOR
        max_mark = marks[i]

print("Highest mark is", max_mark)

5.2 Two‑Dimensional Arrays (Matrices)

// Java – search a seating chart for a free seat
int[][] seats = {
    {0, 1, 0},
    {1, 0, 0},
    {0, 0, 1}
};

boolean free = false;
outer:
for (int r = 0; r < seats.length; r++) {          // rows
    for (int c = 0; c < seats[r].length; c++) {   // columns
        if (seats[r][c] == 0) {                   // nested IF
            free = true;
            break outer;                          // exit both loops
        }
    }
}
System.out.println(free ? "Seat available" : "Full");

6. File Handling (Topic 8.3)

File operations are always performed inside a loop, with nested if statements to test for end‑of‑file, errors, or specific content.

Example – Count lines containing the word “error”

count = 0
try:
    file = open("log.txt", "r")          # open for reading
    while True:                          # outer loop – read until break
        line = file.readline()
        if line == "":                    # inner IF – EOF
            break
        if "error" in line.lower():      # nested IF – keyword test
            count += 1
finally:
    file.close()                         # always close the file
print("Occurrences of ‘error’: ", count)

Using with (recommended)

with open("data.txt", "r") as f:
    for line in f:                       # outer FOR over lines
        if line.strip() == "":           # inner IF – ignore blanks
            continue
        if line.startswith("#"):        # nested IF – comment line
            print(line.rstrip())

7. Simple Database Queries (Topic 9)

7.1 Table definition (pseudo‑SQL)

CREATE TABLE Students (
    StudentID INTEGER PRIMARY KEY,
    Name      VARCHAR(30),
    Mark      INTEGER
);

7.2 SELECT with a nested condition

SELECT Name, Mark
FROM Students
WHERE Mark >= 70          -- outer condition: high achievers
  AND Mark <= 100;        -- inner condition: valid range

7.3 Updating with a nested test

UPDATE Students
SET Grade = CASE
    WHEN Mark >= 70 THEN 'A'
    WHEN Mark >= 55 THEN 'B'
    ELSE 'F'
END;

8. Common Pitfalls & How to Avoid Them

  • Incorrect indentation (Python) or missing braces (Java/C#) – the interpreter/compiler may attach a statement to the wrong block. Always use a consistent style.
  • Infinite loops – ensure the loop’s condition will eventually become false; place a counter or a break inside a nested if when appropriate.
  • Excessive nesting (more than three levels) – reduces readability; extract inner code into a separate function or procedure.
  • Misusing break / continue – they affect only the innermost loop; use a flag variable or labelled break (Java) to exit multiple levels.
  • Off‑by‑one errors in arrays – remember that the first index is 0 in most languages (or 1 in Cambridge pseudocode).
  • File not closed – always close files in a finally block or, better, use a with statement (Python).
  • Logical errors in Boolean expressions – verify with a truth table before replacing nested if with a single expression.

9. Practice Questions (with brief solutions)

  1. Nested if & loops
    Write a Python program that:
    • asks for an integer n (0 < n < 100),
    • prints “Prime” or “Composite”, and
    • if the number is prime, also prints whether it is “Odd” or “Even”.
    Solution outline:
    n = int(input("Enter an integer (0‑99): "))
    if 0 < n < 100:
        is_prime = True
        for i in range(2, int(n**0.5) + 1):
            if n % i == 0:
                is_prime = False
                break          # exit inner loop
        if is_prime:
            print("Prime")
            if n % 2 == 0:
                print("Even")
            else:
                print("Odd")
        else:
            print("Composite")
    else:
        print("Number out of range")
    
  2. Trace the following pseudocode (x = 4)
    IF x > 0 THEN
        IF x < 5 THEN
            PRINT "A"
        ELSE
            PRINT "B"
        ENDIF
    ELSE
        PRINT "C"
    ENDIF
    • x > 0 → True (enter outer IF).
    • x < 5 → True (enter inner IF).
    • Output: A.
  3. Convert nested if to a single Boolean expression
    Using the grading example from the trace table:
    if 0 <= score <= 100 and score >= 70:
        grade = "A"
    elif 0 <= score <= 100:
        grade = "B"
    else:
        grade = "Invalid mark"
    

    Single expression version (Python):

    grade = ("A" if 0 <= score <= 100 and score >= 70 else
             "B" if 0 <= score <= 100 else
             "Invalid mark")
    

    Why the nested version is clearer:

    • Each condition is evaluated step‑by‑step, matching the way a human reads the problem.
    • It highlights the hierarchy (first check validity, then grade), reducing the chance of logical mistakes.
  4. Array & nested loop
    Pseudocode to count marks ≥ 70:
    SET count TO 0
    FOR i FROM 0 TO LENGTH(marks)‑1 DO
        IF marks[i] >= 70 THEN
            SET count TO count + 1
        ENDIF
    ENDFOR
    PRINT "Number of high marks =", count
    
  5. File handling
    Python with block that prints lines starting with “#” while ignoring blank lines:
    with open("data.txt", "r") as f:
        for line in f:                       # outer FOR over lines
            if line.strip() == "":           # inner IF – skip blanks
                continue
            if line.startswith("#"):        # nested IF – comment line
                print(line.rstrip())
    

10. Summary

  • Nested statements allow one control structure to be placed inside another, mirroring real‑world hierarchies and enabling multi‑level decision making.
  • They are essential for:
    • Complex if‑else chains.
    • Loops that need additional checks.
    • Array and matrix processing.
    • File I/O with validation.
    • Simple database queries.
  • Maintain clear indentation (Python) or braces (Java/C#) to avoid logical errors.
  • Limit nesting depth to three levels for readability; otherwise extract code into functions.
  • Always test nested logic with trace tables or truth tables.
  • Remember the supporting Computer Systems concepts (data representation, transmission, hardware, software, and ethics) – they are required for Paper 1 and underpin the programming topics.
Suggested diagram: Flowchart showing an outer IF branching into two inner IF‑ELSE blocks (use standard Cambridge symbols).

Create an account or Login to take a Quiz

44 views
0 improvement suggestions

Log in to suggest improvements to this note.