CIE IGCSE | 8.1.5.1 Nested Selection

Lesson objective

Construct and trace nested IF statements, match ELSE and ENDIF to their IF, and explain which conditions are tested or skipped.

Learn

8.1.5.1 | NESTED SELECTION

01 | A SECOND QUESTION, BUT ONLY SOMETIMES

Imagine arriving at a school event. First, the organiser asks whether you have a ticket. If you do, they ask whether a place is available. If you have no ticket, checking for a place is unnecessary: you cannot enter through this route.

This is nested selection: a selection statement placed inside a branch of another selection statement. Selection chooses instructions according to a condition. A condition produces TRUE or FALSE; a branch is the group of instructions chosen for one of those results.

The outer decision asks about the ticket. The inner decision asks about a place, but only when execution reaches it. Nested does not mean the tests happen at the same time.

02 | START WITH ONE IF

An IF statement evaluates its condition. When that condition is TRUE, it executes the THEN branch. When FALSE, it executes the ELSE branch if one is present. It then continues after ENDIF.

HasTicket is a BOOLEAN variable: it already holds TRUE or FALSE, so it can be used directly as a condition. The example assumes its value has been supplied. At this stage it makes only one decision.

IF HasTicket
  THEN
    OUTPUT "Ticket accepted"
  ELSE
    OUTPUT "A ticket is required"
ENDIF
OUTPUT "Check complete"

03 | PUT AN IF INSIDE THE THEN BRANCH

Now replace the ticket-accepted message with a second decision. SpaceAvailable is also BOOLEAN. The inner IF is part of the outer THEN branch, so it can be reached only when HasTicket is TRUE.

Read the code from top to bottom. Do not jump directly to the space test. First decide whether execution enters the branch containing it.

IF HasTicket
  THEN
    IF SpaceAvailable
      THEN
        OUTPUT "Enter"
      ELSE
        OUTPUT "Please wait"
    ENDIF
  ELSE
    OUTPUT "A ticket is required"
ENDIF
OUTPUT "Check complete"

04 | SEE THE BRANCHES AS CONTAINERS

The inner selection belongs entirely inside the outer TRUE branch. The two ENDIF instructions close different statements. This diagram shows containment; the arrow labels state which result chooses each branch.

OUTER IF | HasTicket

TRUE → THEN

INNER IF | SpaceAvailable

TRUE: output “Enter”

FALSE: output “Please wait”

INNER ENDIF

FALSE → ELSE

Output “A ticket is required”.

The inner IF is skipped.

OUTER ENDIF

After the outer ENDIF: output “Check complete”, whichever branch was chosen. The container layout helps distinguish code inside a branch from code after the whole selection.

05 | TRACE THE THREE POSSIBLE ROUTES

A trace follows the instructions that actually execute for given values. There are four combinations of the two inputs but only three routes through this algorithm.

When HasTicket is FALSE, the value of SpaceAvailable cannot affect the output: its condition is not tested. “Not tested” is different from “tested and FALSE”. Record the distinction.

Only the selected branch executes
HasTicketSpaceAvailableInner test reached?Outputs in order
FALSEFALSENoA ticket is required; Check complete
FALSETRUENoA ticket is required; Check complete
TRUEFALSEYes: FALSEPlease wait; Check complete
TRUETRUEYes: TRUEEnter; Check complete

06 | MATCH EACH ELSE AND ENDIF

The inner ELSE supplies the alternative to the space test. The outer ELSE supplies the alternative to the ticket test. They do not both run when the inner condition is FALSE.

If the ticket is present but no space is available, the inner ELSE outputs “Please wait”. Execution then leaves the inner selection. It remains within the outer THEN route and skips the outer ELSE because the ticket test was TRUE.

Each IF needs its own ENDIF. Match an ENDIF to the nearest IF that is still open. Match an ELSE to its surrounding IF, not to whichever condition appears most relevant in the story.

07 | INDENTATION MAKES THE STRUCTURE VISIBLE

Indentation means placing spaces at the start of a line to show structure. In Cambridge pseudocode, nested IF statements continue the two-space indentation pattern. An inner IF moves further right because it belongs to an outer branch.

Align each ELSE and ENDIF with its own IF. In the code above, the inner IF, its ELSE and its ENDIF share a level; the outer three share another. This makes the pairing visible before you read the conditions.

Indentation supports understanding, but correct keywords and placement are still essential. Making a wrongly placed ENDIF look tidy does not fix the algorithm.

08 | TRY AN INTERACTIVE TRACE

Choose the inputs, then step through the actual route. Notice that the inner condition never appears in the trace when the ticket is absent. Resetting begins a fresh trace; change the inputs to compare another route.

    09 | NESTING CAN GO IN AN ELSE BRANCH

    Sometimes the second question is needed after the first condition is FALSE. An exam result might be a distinction at eighty or above, a pass at fifty or above, and otherwise not a pass.

    The first test identifies the highest band. Only scores below eighty reach the second test. Therefore the inner TRUE branch means fifty to seventy-nine for whole-number scores, even though its own condition mentions only fifty.

    Assume Score is an INTEGER from zero to one hundred. The upper bound of the pass band comes from the route taken to reach its test.

    IF Score >= 80
      THEN
        OUTPUT "Distinction"
      ELSE
        IF Score >= 50
          THEN
            OUTPUT "Pass"
          ELSE
            OUTPUT "Not a pass"
        ENDIF
    ENDIF

    10 | FOLLOW THE SCORE BOUNDARIES

    For eighty, the outer test is TRUE, so “Distinction” is output and the pass test is skipped. For seventy-nine, the outer test is FALSE but the inner test is TRUE, so “Pass” is output.

    Testing just a typical value such as sixty is not enough. Forty-nine, fifty, seventy-nine and eighty check the points where a category changes. A trace should show the condition results as well as the final message.

    Outer decisions determine which inner decisions are reached
    ScoreScore >= 80Score >= 50 reached?Output
    49FALSEYes: FALSENot a pass
    50FALSEYes: TRUEPass
    79FALSEYes: TRUEPass
    80TRUENoDistinction

    11 | TWO SEPARATE IFS ARE A DIFFERENT STRUCTURE

    Two IF statements placed one after another are sequential selections, not nested selections. After the first finishes, the second is reached independently.

    With Score equal to eighty-five, both comparisons below are TRUE, so both messages are output. That differs from the nested category example, which outputs only “Distinction”. Neither pattern is always wrong: choose according to whether several actions or exactly one category are required.

    IF Score >= 80
      THEN
        OUTPUT "Distinction"
    ENDIF
    IF Score >= 50
      THEN
        OUTPUT "Pass"
    ENDIF

    12 | AND CAN HELP, BUT DOES NOT REPLACE EVERY NEST

    If the only action is to admit someone who has a ticket and a space, a single condition HasTicket AND SpaceAvailable can be clearer. However, the earlier nested example gives different explanations for a missing ticket and a full event.

    A simple IF with that AND condition and one generic ELSE would not preserve all three messages. Choose the structure by the required behaviour, not just by the number of lines.

    Nested selection is also useful when a later operation must be reached only after a safety test. To avoid dividing by zero, test the count before calculating an average. Do not depend on an assumed short-circuit rule for a combined logical expression.

    13 | A GUARD BEFORE A SECOND DECISION

    Suppose Total is a REAL running total and Count is an INTEGER number of results. Count is non-negative. A guard is a check that must succeed before an operation is allowed.

    The outer condition guards the division. If Count is zero, the calculation and the average test are both skipped. If Count is positive, the program calculates Average and then decides whether it reaches fifty. Average is never read on the no-results route.

    DECLARE Average : REAL
    IF Count > 0
      THEN
        Average ← Total / Count
        IF Average >= 50
          THEN
            OUTPUT "Average meets the target"
          ELSE
            OUTPUT "Average below the target"
        ENDIF
      ELSE
        OUTPUT "No results to average"
    ENDIF

    14 | PREVENT COMMON NESTING ERRORS

    Testing an unreachable condition: work through the outer branch first. Do not evaluate every condition just because it appears on the page.

    Running both ELSE branches: the inner FALSE result does not change the already chosen outer branch.

    Closing the outer IF too early: placing an ENDIF before the intended inner statement moves that statement outside the branch and changes when it runs.

    Repeated independent category tests: two separate IF statements can both output a category. Use nested alternatives when exactly one category is required.

    Reading an unassigned value: if Average is assigned only in the positive-count branch, do not output it unconditionally after ENDIF. The zero-count route has no calculated average.

    15 | PLAN THE ROUTES BEFORE WRITING THE CODE

    Ask three questions: What is the first decision? Which branch needs another decision? Where should all routes rejoin? Write the outer structure first, then place the inner structure inside the chosen branch.

    For each route, predict the conditions tested, the conditions skipped and the outputs in order. Include boundary values for numeric tests and both Boolean values where relevant.

    A useful explanation is: “The ticket condition is FALSE, therefore execution takes the outer ELSE branch. The space condition is inside the outer THEN branch, so it is not tested.” This explains the control flow rather than merely naming the final message.

    The next lesson explores nested iteration, where a loop is placed inside another loop. Nested selection chooses routes; nested iteration repeats instructions.

    MATCH THE LINE TO ITS ROLE

    Terminology

    Terminology

    Selection

    Choosing instructions according to a condition.

    Nested selection

    A selection statement inside a branch of another selection statement.

    Condition

    An expression evaluated to TRUE or FALSE.

    BOOLEAN

    A type with the values TRUE and FALSE.

    Branch

    Instructions belonging to one outcome of a decision.

    Outer IF

    A selection statement containing another selection.

    Inner IF

    A selection statement contained inside a branch of another.

    THEN

    Introduces the instructions chosen when an IF condition is TRUE.

    ELSE

    Introduces the alternative instructions when its IF condition is FALSE.

    ENDIF

    Closes its corresponding IF statement.

    Indentation

    Leading spaces that show the structure of instructions.

    Trace

    A step-by-step record of the instructions actually executed.

    Control flow

    The route taken through the instructions of an algorithm.

    Skipped condition

    A condition whose statement is not reached on the chosen route.

    Sequential selections

    Separate selection statements executed one after another.

    Boundary value

    A value at a limit where behaviour can change.

    Guard

    A condition checked before allowing a later operation.

    Common continuation

    Instructions after a selection reached once the chosen branch completes.

    Questions

    Questions

    CHECK YOUR UNDERSTANDING

    Select all correct choices. Each exact set earns one point.

    1. Which describes nested selection?
    2. HasTicket is FALSE. Which statements apply to the event example?
    3. HasTicket TRUE, SpaceAvailable FALSE. Which messages are output?
    4. Which practices help show structure?
    5. Score is 80 in the nested category example. What happens?
    6. Which scores output Pass in the nested category example?
    7. What happens with two independent category IF statements and Score 85?
    8. Count is zero in the average example. Which statements apply?

    EXPLAIN AND COMPARE

    Write your answers before revealing each sample.

    1. Define nested selection.

    2. Explain why SpaceAvailable is not tested when HasTicket is FALSE.

    3. Describe the outputs when HasTicket is TRUE and SpaceAvailable is FALSE.

    4. Explain how to match the ELSE and ENDIF keywords in a nested IF.

    5. Compare nested category selection with two independent IF statements for Score 85.

    6. Trace the nested grade example for 49, 50, 79 and 80.

    7. Explain why the Count test prevents division by zero.

    8. Suggest why a single ticket AND space condition might not replace the original behaviour.

    BUILD IT | A LIBRARY LOAN

    A library first checks whether MemberActive is TRUE. If not, output “Renew membership”. For an active member, check whether Loans is below five. Output “Loan allowed” when below five and “Return a book first” otherwise. Assume MemberActive is BOOLEAN and Loans is a valid non-negative INTEGER. Output “Check complete” after every route. Write nested selection and test inactive membership, then active membership with four and five loans.

    Reveal one possible solution
    IF MemberActive
      THEN
        IF Loans < 5
          THEN
            OUTPUT "Loan allowed"
          ELSE
            OUTPUT "Return a book first"
        ENDIF
      ELSE
        OUTPUT "Renew membership"
    ENDIF
    OUTPUT "Check complete"

    Inactive: Renew membership, then Check complete; the loan test is skipped. Active with four loans: Loan allowed, then Check complete. Active with five loans: Return a book first, then Check complete. A loan is permitted only below five, because allowing it at five would exceed the limit.

    Flashcards

    Flashcards

    Click to flip. Select the ideas you need to revisit.

    0 cards selected for revision.

      Selections are kept while this page is open.

      Workbook

      Workbook

      COMING SOON

      The workbook for 8.1.5.1 Nested Selection is coming soon. Complete the matching task and written questions in your exercise book.