Study Guide

Selection

How a program chooses what to do: IF with and without ELSE, conditions built with operators, IF statements nested inside each other (up to three levels), and CASE, with how to choose between them.

Lesson 5.4 Algorithms and Programming

For: Cambridge IGCSE Computer Science learners, or Key Stage 3 learners who have met variables and operators (about ages 13 to 14)

Stage: Think

A rule with a choice in it

Splashdown, a fictional water park, has a fast slide. The attendant checks each rider’s height. Riders must be at least 120 cm tall to use it; shorter riders are sent to the small slide.

Think it through

Write the attendant’s rule in a form a computer could follow: what is checked, and what happens in each case?

Show a model answer

Check: is the rider’s height at least 120 cm? If yes, they use the fast slide. If no, they are sent to the small slide. One check leads to one of two different actions, and only one of them happens each time.

Stage: Predict

Doing something only sometimes

A program that always carries out every line, in order, cannot make a choice. Selection lets a program carry out some instructions only when a condition (a test that is true or false) is met. Here a fictional canteen takes 50 pence off an order of more than 500 pence. Money is in whole pence.

INPUT Total
IF Total > 500
  THEN
    Total ← Total - 50
ENDIF
OUTPUT Total

Think it through

Predict the output when Total is 620, and when Total is 500. Explain what the IF line decides.

Show a model answer

For 620 the output is 570: 620 > 500 is true, so the line inside the IF runs, taking 50 off. For 500 the output is 500: 500 > 500 is false, so the line inside is skipped. The IF line decides whether the indented line runs. The OUTPUT is after ENDIF, so it always runs.

An IF … THEN … ENDIF statement carries out the instructions between THEN and ENDIF only when the condition is true. When the condition is false the computer jumps to the line after ENDIF, and nothing else happens. Check this with a trace table; each row is a separate run.

Following the discount program: one row for each order
Total enteredIs Total > 500?OUTPUT
620
500
480

    Show the completed table
    Total enteredIs Total > 500?OUTPUT
    620Yes570
    500No500
    480No480

    Check your understanding

    In the discount program, what happens when the condition is false and there is no ELSE?
    Show the answer

    Answer: A. The lines between THEN and ENDIF are skipped and the program carries on.

    A false condition is not a failure: the guarded lines are skipped.

    Stage: Discover

    Two ways to go

    Sometimes there is something to do in both cases, as with the slide attendant. A fictional number-guessing game keeps the secret number in a constant and gives feedback:

    CONSTANT Target ← 7
    DECLARE Guess : INTEGER
    INPUT Guess
    IF Guess = Target
      THEN
        OUTPUT "Correct"
      ELSE
        OUTPUT "Try again"
    ENDIF

    Think it through

    When does “Try again” appear? Describe, in your own words, how ELSE differs from a second IF that tests whether the guess is wrong.

    Show a model answer

    “Try again” appears whenever Guess is anything other than 7. ELSE has no condition of its own: it is carried out exactly when the IF’s condition is false. A second test such as Guess <> Target would give the same result but would repeat work that the IF has already done, and could be written wrongly.

    In IF … THEN … ELSE … ENDIF, exactly one of the two blocks runs each time: the THEN block when the condition is true, the ELSE block when it is false. The condition may be built with the logical operators from Lesson 3. This fictional ride lets a visitor on only if they pass both checks:

    IF Height >= 120 AND Age >= 8
      THEN
        OUTPUT "Welcome aboard"
      ELSE
        OUTPUT "Sorry, not this ride"
    ENDIF

    ELSE has no condition. It means “otherwise”: whatever the IF’s condition did not catch. Writing ELSE Guess <> Target is a mistake. Also, in a condition = means “is equal to”, but a value is stored with ←: IF Score = 10 is a test; Score ← 10 is an assignment.

    Check your understanding

    A visitor is 125 cm tall and 7 years old. What does the ride program output?
    Show the answer

    Answer: C. Sorry, not this ride, because AND needs both tests true and Age >= 8 is false.

    For AND, one false test makes the whole condition false.

    Stage: Discover

    Choices inside choices

    Splashdown’s entry price depends on age: under 5 is free, ages 5 to 15 pay 400 pence, and everyone else pays 700 pence. That is three outcomes, and one IF can only choose between two.

    Think it through

    How could you use two-way choices to decide between three outcomes? Describe your plan in words before you write any pseudocode.

    Show a model answer

    Make one choice first: is the age under 5? If so, the price is 0. If not, make a second choice about the people who are left: is the age 15 or under? If so, 400, otherwise 700. The second choice is inside the “otherwise” of the first.

    An IF statement placed inside another is nested. The syllabus’s limit is three levels of nesting.

    1. List the outcomes and who gets each. Free: under 5. 400 pence: 5 to 15. 700 pence: 16 and over. Three outcomes, so two decisions are needed.
    2. Test the first group first. Age < 5 separates the under-5s from everyone else.
    3. Use the ELSE for “everyone else”, and make the second decision there. Anyone who reaches the ELSE is at least 5 already, so the second test does not need to say so again: Age <= 15 is enough to pick out 5 to 15.
    4. The last ELSE gets the remaining group. Anyone who is not under 5 and not 15 or under must be 16 or over.
    INPUT Age
    IF Age < 5
      THEN
        Price ← 0
      ELSE
        IF Age <= 15
          THEN
            Price ← 400
          ELSE
            Price ← 700
        ENDIF
    ENDIF
    OUTPUT Price

    Each IF has its own ENDIF, and the inner IF is indented two spaces further than the one it sits in. Trace the edge ages 4, 5, 15 and 16 to check it.

    Check your understanding

    What does the entry-price program output for a visitor aged 16?
    Show the answer

    Answer: C. 700

    Follow the decisions from the outside inwards.

    Now a second nested program, a fictional grade calculator. Marks run from 0 to 100.

    INPUT Mark
    IF Mark >= 70
      THEN
        OUTPUT "Distinction"
      ELSE
        IF Mark >= 50
          THEN
            OUTPUT "Merit"
          ELSE
            IF Mark >= 40
              THEN
                OUTPUT "Pass"
              ELSE
                OUTPUT "Fail"
            ENDIF
        ENDIF
    ENDIF

    Fill in the trace. Leave a cell empty when the test is never reached, because an earlier test has already decided.

    Following the grade calculator: one row for each pupil
    MarkMark >= 70?Mark >= 50?Mark >= 40?OUTPUT
    75
    55
    40
    39

      Show the completed table
      MarkMark >= 70?Mark >= 50?Mark >= 40?OUTPUT
      75YesDistinction
      55NoYesMerit
      40NoNoYesPass
      39NoNoNoFail

      Apply it

      A programmer rewrites the grade calculator and tests Mark >= 40 first (with Pass in its THEN block), then Mark >= 50, then Mark >= 70, nesting each in the ELSE of the one before. What does a pupil with 75 now get?
      Show the answer

      Answer: A. Pass

      In a nested IF, the first true test decides; test the most demanding group first.

      Stage: Predict

      Choosing from a list

      The canteen has a numbered menu: 1 is a burger, 2 is a pizza and 3 is a salad. The pupil types a number.

      INPUT Choice
      CASE OF Choice
        1 : OUTPUT "Burger"
        2 : OUTPUT "Pizza"
        3 : OUTPUT "Salad"
        OTHERWISE OUTPUT "No such item"
      ENDCASE

      Think it through

      Predict the output for Choice = 3, and for Choice = 7. How does this program differ from three separate IF statements?

      Show a model answer

      For 3 the output is Salad; for 7 it is “No such item”. A CASE statement looks at one variable, compares it with each listed value in turn, and carries out the line for the first one that matches. OTHERWISE catches every value that is not listed. It does the work of a chain of IFs, but reads more clearly as a list.

      A CASE OF … ENDCASE statement chooses one of several branches according to the value of one variable. The branches are tested in order; when one matches, only its statement runs and the rest are not tested. If an OTHERWISE clause is written, it must come last and runs when no value matches. Without OTHERWISE, an unlisted value means that nothing happens.

      Do not confuse: IF or CASE?

      Use whenIF
      The decision is a test of any kind: a range, a comparison or several conditions joined with AND or OR.Mark >= 50, or Height >= 120 AND Age >= 8.
      Use whenCASE
      One variable is compared with a list of exact values, one branch for each.A menu number, a day number, a key pressed.

      A CASE branch holds one exact value. A range such as 50 to 69 is a job for IF. Keep each branch to a single statement; if the branches are long or complicated, the syllabus advises using IF.

      Apply it

      A program turns a day number from 1 to 7 into the name of the day (1 is Monday, 2 is Tuesday and so on) and says “Invalid day” for any other number. Which selection statement is the clearest fit?
      Show the answer

      Answer: B. CASE OF DayNumber, one branch for each day, and OTHERWISE for “Invalid day”.

      One variable compared with exact values: CASE. A range or a combined test: IF.

      Stage: Apply

      Finding the fault

      A teacher in a fictional school writes a program to tell pupils whether they passed (50 or more) and whether they earned a distinction (70 or more).

      INPUT Mark
      IF Mark >= 50
        THEN
          OUTPUT "Pass"
      ENDIF
      IF Mark >= 70
        THEN
          OUTPUT "Distinction"
      ENDIF

      Think it through

      A pupil scores 75. What does the program output, and what is wrong with that?

      Show a model answer

      It outputs two lines: “Pass” and then “Distinction”. The two IF statements are separate, so both conditions are tested, and 75 is true for both. The program should give one result for a pupil. For a distinction, “Pass” should not also appear.

      Apply it

      Which change makes the program output exactly one word for every mark: Distinction for 70 or more, Pass for 50 to 69, and nothing below 50?
      Show the answer

      Answer: A. Nest the Pass test in the ELSE of the Distinction test, so Distinction is tested first.

      Separate IF statements are all tested; a nested IF with ELSE lets only one block run.

      Think it through

      Write pseudocode that inputs a whole-number temperature in degrees Celsius and outputs “Freezing” if it is below 0, “Cold” if it is from 0 to 14, and “Warm” otherwise. Then say how many IF statements you used and why.

      Show a model answer
      INPUT Temperature
      IF Temperature < 0
        THEN
          OUTPUT "Freezing"
        ELSE
          IF Temperature < 15
            THEN
              OUTPUT "Cold"
            ELSE
              OUTPUT "Warm"
          ENDIF
      ENDIF

      Two IF statements, nested: three outcomes need two decisions. After the first test, a value is at least 0, so the second only needs Temperature < 15. Test the values at the edges (-1, 0, 14, 15) to check: Freezing, Cold, Cold, Warm.

      Go deeper The same ideas in Python
      temperature = int(input())
      if temperature < 0:
          print("Freezing")
      elif temperature < 15:
          print("Cold")
      else:
          print("Warm")
      • A colon (:) ends the line with the condition, and indentation shows what belongs to each branch. There is no THEN or ENDIF.
      • Python has elif (“else if”) so a chain of choices stays flat. In pseudocode each further choice is nested inside the ELSE above it, which the syllabus limits to three levels.
      • Equality is tested with ==, not =: if choice == 3:. Using a single = in a condition is an error in Python.
      • and, or and not are in lower case.
      • Python 3.10 and later also have match … case, similar to CASE, with case _: playing the part of OTHERWISE; an if … elif … else chain works in every version.

      Stage: Consolidate

      Show what you know

      Think it through

      Explain to a friend why a program needs selection, and when you would choose CASE rather than IF. Give an example of each from a school setting.

      Show a model answer

      A good answer says that without selection a program does the same instructions every time, whatever the data, and that selection lets it choose by testing a condition. IF suits any test, such as a range (“a mark of 50 or more passes”). CASE suits one variable with a list of exact values, such as a numbered menu in the canteen or a day number.

      Apply it

      A fictional library charges nothing if a book is returned on time (DaysLate = 0), 10 pence a day for up to 7 days late, and a flat 100 pence if it is more than 7 days late. How many IF statements does a correct nested solution need, and why?
      Show the answer

      Answer: C. Two: one decision for on time or late, and one for up to 7 days late or more.

      For n outcomes a nested IF needs n - 1 decisions.

      • Selection lets a program carry out instructions only when a condition is true.
      • IF … THEN … ENDIF guards a block: if the condition is false, the block is skipped. Adding ELSE gives a block for the false case; exactly one of the two blocks runs. ELSE has no condition of its own.
      • Conditions use the relational operators (=, <>, <, <=, >, >=) and AND, OR and NOT. A value is stored with ←, but compared with =.
      • IF statements can be nested: put the next decision in the ELSE of the last. Three outcomes need two decisions; test one group at a time, most demanding first; the syllabus’s limit is three levels.
      • CASE OF … OTHERWISE … ENDCASE compares one variable with a list of exact values; use IF for ranges and combined tests.
      • Check edges (such as exactly 50) when tracing.

      Sources and scope

      • What this lesson is. The fourth lesson of the Algorithms and Programming module, written for this site. It covers points 8.1.4(b) and 8.1.5 (nested selection) of Cambridge IGCSE Computer Science 0478 (2026 to 2028, version 6). Its curriculum links are provisional and imply no review or endorsement by any examination board.
      • Original material. Splashdown, the canteen, the guessing game, the grade calculator, the temperature program, the library and the school are fictional, written for this lesson. The pseudocode follows the layout in the syllabus’s pseudocode guide, with THEN, ELSE and the CASE branches indented by two spaces, and each program’s output was worked out by hand.
      • Simplified on purpose. The programs assume that the user types a sensible whole number; checking input (validation) is left to a later lesson. Nesting is kept to the syllabus’s three levels. Python’s match statement is mentioned in one line only.
      • Left to later lessons. Iteration and nested iteration (Lesson 5); totalling, counting and finding the highest and lowest values (Lesson 6).