[8.1.5] Nested Statements

[8.1.5] Nested Statements

What are nested statements?

Nested statements are control structures placed inside other control structures. In IGCSE Computer Science, you will most often nest selection (IF...THEN...ELSEIF...ELSE) inside selection, or iteration (FOR, WHILE, REPEAT UNTIL) inside iteration, or combine the two (for example, an IF inside a loop). Nesting lets a program make more precise decisions or repeat more detailed sets of steps.

The syllabus expects you to understand and use nested selection and iteration, up to a practical limit of no more than three levels of nesting. Deep nesting can be hard to read and maintain, so you should develop habits that keep structure clear: choose meaningful conditions, group related steps, and add parentheses and indentation consistently.

Why do we nest?

Nesting solves multi-stage decisions and layered repetition. For example, a shop may first check a customer's age, then if they have a loyalty card, then apply a discount. Likewise, when printing a calendar grid, you repeat over weeks, and inside each week you repeat over days. These are naturally nested processes that would be awkward without nesting.

Nesting selection (IF inside IF)

Nesting selection is useful when one decision depends on the outcome of a previous decision. Keep conditions specific and avoid overlapping ranges. Prefer ELSEIF chains for mutually exclusive branches, and use a final ELSE for an “otherwise” case.

Scenario: A grade depends first on whether the mark is valid (0 to 100 inclusive). If valid, assign grade bands. If not valid, output an error. This is nesting because the grade checks only occur inside the “valid” branch.

Structure (pseudocode sketch):

  • IF mark is between 0 and 100 THEN
  • IF mark >= 70 THEN grade A ELSEIF mark >= 60 THEN grade B ... ELSE grade F ENDIF
  • ELSE output “Invalid mark”
  • ENDIF

When only one grade should apply, an ELSEIF chain is often clearer than many IF statements nested at the same level. The chain expresses a mutually exclusive set of ranges and avoids checking more conditions than necessary.

  • IF mark >= 70 THEN grade A
  • ELSEIF mark >= 60 THEN grade B
  • ELSEIF mark >= 50 THEN grade C
  • ELSE grade F
  • ENDIF

Combine this with a guard IF around the whole chain to validate input first.

Edge risk: overlapping ranges or missing boundaries can produce unexpected results. For example, using > 70 in one branch and >= 70 in another may cause the same mark to match two different branches or to match none. Always specify inclusive or exclusive boundaries carefully and consider testing boundary values such as 0, 100, and cut-offs like 70 and 60.

Nesting iteration (loops inside loops)

Nested iteration repeats an inner process for every step of an outer process. Typical uses include table generation (rows and columns), searching a 2D structure, or combining items from two lists. Limit nesting to necessary levels and include clear loop counters.

Rows and columns: An outer loop controls the row number; an inner loop prints each column entry for that row. This pattern underpins multiplication tables, seating charts, and simple grids.

Conditional inner work: The inner loop may include an IF to format or filter. For example, when printing a times table, you might mark perfect squares specially when row = column.

Three levels maximum: For example, week → day → lesson slot when building a timetable. Keep names and indentation clear. If you feel tempted to add a fourth level, consider refactoring into a procedure or flattening logic.

Combining selection and iteration

Real problems often combine loops and decisions. For instance, while reading a list of temperatures, an outer loop steps through the data and an inner IF counts how many are above a threshold. Another common structure is input validation: repeat asking for input (loop) until it satisfies a condition (IF).

Goal: obtain a valid mark between 0 and 100 inclusive. Use a loop that continues until the input is valid. The IF sets a flag or decides whether to continue. This is a classic nested selection inside iteration.

Goal: count how many values exceed a threshold. For each item in the loop, an IF condition updates the count. This nests selection inside iteration and demonstrates accumulator patterns.

Goal: run a FOR loop only when a precondition holds. For example, only generate a table when the requested size is between 1 and 12 inclusive. Here, selection controls whether the iteration executes at all.

Design tips for readable nesting

  • Guard first: check for invalid or trivial cases at the top with an IF, so the main logic is cleaner.
  • Prefer ELSEIF chains to multiple nested IF blocks when only one branch should run.
  • Limit depth: aim for no more than three levels. Extract repeated or complex steps into procedures or functions.
  • Name counters and flags meaningfully, e.g. row, col, isValid.
  • Test boundaries: values at the edges of ranges often reveal nesting mistakes.

Common patterns to master

Pattern Outer structure Inner structure Typical use
Validation loop REPEAT...UNTIL input valid IF invalid THEN prompt again Obtain a valid mark, age, or menu choice
Counter with condition FOR each item IF meets criterion THEN count ← count + 1 Tally occurrences of values above a threshold
2D traversal FOR row ← 1 TO R FOR col ← 1 TO C Grids, seating plans, multiplication tables
Tiered decision IF valid input ELSEIF chain to select band Grades, shipping bands, age-based prices

Deep Dive: Avoiding the “arrow shape”

Deeply nesting IF inside IF can create a right-slanting “arrow” of indentation that is hard to read. To avoid this, apply guard clauses (validate and handle invalid cases early), use ELSEIF for mutually exclusive tests, and move repeated logic into a procedure. If the inner logic depends on a value that you can compute once, calculate it before the decision to reduce inner complexity.

Deep Dive: Loop invariants and termination

When nesting loops, ensure each loop has a clear invariant (what stays true each time) and a correct termination condition. For instance, in a two-loop grid print, the inner loop must reset its counter each time the outer loop advances, and both counters must eventually reach their limits. Off-by-one mistakes in either loop can break the overall structure.

Worked examples with copy support

// CAIE-style pseudocode: validation loop (nested selection in iteration)
DECLARE mark : INTEGER
REPEAT
    INPUT mark
    IF (mark < 0) OR (mark > 100) THEN
        OUTPUT "Invalid. Enter 0..100."
    ENDIF
UNTIL (mark >= 0) AND (mark <= 100)

// CAIE-style pseudocode: 2D traversal (nested iteration)
DECLARE row : INTEGER
DECLARE col : INTEGER
FOR row ← 1 TO 3
    FOR col ← 1 TO 3
        OUTPUT row * col
    NEXT col
NEXT row
# Python equivalents
# Validation loop (repeat-until emulated)
while True:
    mark = int(input())
    if (mark < 0) or (mark > 100):
        print("Invalid. Enter 0..100.")
    else:
        break

# 2D traversal
for row in range(1, 4):
    for col in range(1, 4):
        print(row * col)

 Key Takeaways

  • Nesting means placing one control structure inside another to express layered decisions or repetition.
  • Use nested selection for tiered decisions and nested iteration for grid-like or combinational tasks.
  • Prefer ELSEIF chains for mutually exclusive ranges and include a final ELSE where appropriate.
  • Keep to no more than three levels; extract complex logic into procedures to improve readability.
  • Combine loops and decisions carefully: validate inputs, maintain clear counters, and test boundary conditions.
  • Reduce the “arrow shape” by guarding invalid cases early and computing helper values before branching.