A-Level Computer Science / Unit 11: Structured Programming

11.2.1 IF, ELSE and Nested Decisions

🔒 Lesson slides are available to signed-in users. Sign in

11.2.1 IF, ELSE and Nested Decisions

Selection allows an algorithm to choose which statements should run. The path followed depends on whether a Boolean condition evaluates to TRUE or FALSE.

This section develops one-way decisions, two-way decisions and nested decisions. Multi-way selection using CASE is taught separately in Section 11.2.2.

By the end of this section, you should be able to:

  • Explain how a condition controls program flow.
  • Write and trace a one-way IF statement.
  • Use IF...ELSE for two mutually exclusive paths.
  • Use comparison and logical expressions as conditions.
  • Write nested IF statements using correct indentation.
  • Explain why the order of nested tests can affect the outcome.
  • Distinguish nested selection from separate independent decisions.
  • Trace the exact statements executed for supplied input values.
Connection to 11.1.3: that page explained how Boolean expressions are evaluated. Here, those Boolean results determine which branch of an algorithm is executed.

Selection Changes the Path Through an Algorithm

Without selection, statements normally execute in sequence. A selection construct introduces alternative paths.

Selection: a control structure that chooses which statement or block of statements to execute according to a condition.
Branch: one possible path through a selection structure.
Stage What happens
Evaluate the condition The Boolean expression produces TRUE or FALSE
Select a path The result determines which block is entered
Execute the branch Only the statements belonging to the selected path run
Continue Execution resumes after the complete selection structure
Common misconception: the condition does not itself perform the action. It only produces a Boolean result that determines whether a branch is followed.

One-way IF Statements

A one-way IF contains an optional block. The block runs when the condition is true and is skipped when the condition is false.

General pattern

IF <Condition>
THEN
    <Statement or statements>
ENDIF

Original example: equipment cooling

IF BatteryTemperature > 48
THEN
    OUTPUT "Activate the cooling fan"
ENDIF
BatteryTemperature Condition result Effect
53 TRUE The message is displayed
48 FALSE The output statement is skipped
41 FALSE The output statement is skipped

When the condition is false, execution continues with the first statement after ENDIF.

Use a one-way IF when an action is required only in one situation and no alternative action is needed.

Two-way Decisions with IF and ELSE

An ELSE branch provides an alternative action when the original condition is false.

General pattern

IF <Condition>
THEN
    <Statements for TRUE>
ELSE
    <Statements for FALSE>
ENDIF

Original example: parcel handling

IF ParcelMass <= 22
THEN
    OUTPUT "Use the standard conveyor"
ELSE
    OUTPUT "Send for manual handling"
ENDIF
ParcelMass ParcelMass <= 22 Branch followed Output
17 TRUE THEN Use the standard conveyor
22 TRUE THEN Use the standard conveyor
22.4 FALSE ELSE Send for manual handling
Mutually exclusive branches: branches where executing one prevents the other from executing during the same decision.
Common mistake: do not attach another condition to ELSE. The ELSE branch already represents every situation in which the original condition is false.

Checking Boundary Conditions

Many selection errors occur at a boundary: the exact value where the result changes from one branch to another.

Phrase Suitable comparison Is the boundary included?
Above 30 Value > 30 No
At least 30 Value >= 30 Yes
Below 30 Value < 30 No
No more than 30 Value <= 30 Yes

Boundary trace

IF FileSize <= 25
THEN
    OUTPUT "Upload permitted"
ELSE
    OUTPUT "File too large"
ENDIF

A file size of exactly 25 follows the THEN branch because the equality part of <= includes the limit.

Always test a value below the boundary, the boundary itself and a value above it.

Nested IF Statements

A nested decision places one IF structure inside a branch of another IF. The inner condition is evaluated only if execution reaches it.

Nested IF: an IF structure contained inside another selection branch.

Original example: workshop access

IF HasReservation = TRUE
THEN
    IF SafetyTrainingComplete = TRUE
    THEN
        OUTPUT "Workshop access granted"
    ELSE
        OUTPUT "Complete the safety training"
    ENDIF
ELSE
    OUTPUT "A reservation is required"
ENDIF
HasReservation SafetyTrainingComplete Conditions evaluated Output
FALSE TRUE or FALSE Only the outer condition A reservation is required
TRUE FALSE Outer and inner conditions Complete the safety training
TRUE TRUE Outer and inner conditions Workshop access granted

When HasReservation is false, the inner condition is not evaluated because execution never enters the outer THEN branch.

Common mistake: do not assume that every condition in a nested structure is always tested. An inner condition is reached only through its containing branch.

The Order of Tests Matters

Nested conditions are often used to divide values into several ranges. The order must ensure that each value reaches the correct outcome.

Original example: storage classification

IF StorageUsed < 40
THEN
    OUTPUT "Low usage"
ELSE
    IF StorageUsed < 80
    THEN
        OUTPUT "Moderate usage"
    ELSE
        OUTPUT "High usage"
    ENDIF
ENDIF
Output Effective range Reason
Low usage StorageUsed < 40 The first condition is true
Moderate usage 40 <= StorageUsed AND StorageUsed < 80 The first test failed, but the second is true
High usage StorageUsed >= 80 Both tests are false

Why reversing the tests causes a problem

IF StorageUsed < 80
THEN
    OUTPUT "Moderate usage"
ELSE
    IF StorageUsed < 40
    THEN
        OUTPUT "Low usage"
    ENDIF
ENDIF

A value of 25 satisfies StorageUsed < 80, so the inner condition is never reached. The “Low usage” outcome has become unreachable.

For ordered numeric categories, test thresholds in a logical order and derive the effective range of each branch.

Nested or Independent Decisions?

Two separate IF statements are not the same as an IF...ELSE structure. Separate conditions are evaluated independently, so both blocks may execute.

Two independent IF statements

IF IsMember = TRUE
THEN
    Discount ← 5
ENDIF

IF HasVoucher = TRUE
THEN
    Discount ← Discount + 3
ENDIF

When both conditions are true, both statements run and the total discount is increased twice.

Mutually exclusive branches

IF IsMember = TRUE
THEN
    Discount ← 5
ELSE
    Discount ← 0
ENDIF

Here, exactly one assignment runs.

Structure How many conditions are evaluated? Can more than one action run?
Separate IF statements Every independent condition Yes
IF...ELSE One condition No: exactly one branch runs
Nested IF Only conditions reached along the chosen path One path through each reached decision
Replacing two independent IF statements with IF...ELSE can change the behaviour of the algorithm.

A Reliable Method for Tracing Selection

Stage Action Useful question
1. Record values Write the current value of every identifier used by the condition What data is available before the decision?
2. Substitute Replace identifiers in the condition with their current values What exact comparison is being evaluated?
3. Evaluate Determine whether the condition is true or false Which branch is selected?
4. Execute Follow only the statements in the chosen branch Are any variables or outputs changed?
5. Continue Move to the statement after the matching ENDIF Which selection level has just ended?
In a nested decision, record whether an inner condition was true, false, or not evaluated.

Worked Example: Drone Launch Check

A drone may launch only when the weather is safe. If the weather is safe, the battery must also contain at least 70 percent charge.

Pseudocode

IF IsWeatherSafe = TRUE
THEN
    IF BatteryLevel >= 70
    THEN
        OUTPUT "Launch approved"
    ELSE
        OUTPUT "Recharge the battery"
    ENDIF
ELSE
    OUTPUT "Delay the launch"
ENDIF

Trace using sample values

IsWeatherSafe = TRUE
BatteryLevel = 64
Stage Condition Result Effect
Outer decision IsWeatherSafe = TRUE TRUE Enter the outer THEN branch
Inner decision 64 >= 70 FALSE Enter the inner ELSE branch
Output Display “Recharge the battery”

Other possible paths

IsWeatherSafe BatteryLevel Output
FALSE Any value Delay the launch
TRUE Below 70 Recharge the battery
TRUE 70 or above Launch approved
Notice that the battery condition is irrelevant when the weather condition is false because the inner decision is not reached.

Interactive: Selection Path Visualiser

Choose a decision structure, change its inputs and watch the executed path. The trace control highlights each reached line in order.

Ventilation starts only when humidity is above 68%.

IF Humidity > 68
THEN
OUTPUT "Start ventilation"
ENDIF
Branch taken THEN branch

72 > 68 is TRUE, so the optional block executes.

Output: Start ventilation
During a trace, distinguish between a condition that evaluates to false and a condition that is never reached.

Common Mistakes and Misconceptions

  • Adding a condition after ELSE: ELSE is already the fallback for a false condition.
  • Executing both branches: an IF...ELSE structure follows exactly one branch.
  • Ignoring the boundary: using > where the requirement includes the limiting value.
  • Testing every nested condition: inner conditions may be skipped when their containing branch is not entered.
  • Testing thresholds in the wrong order: a broad first condition may make a later branch unreachable.
  • Misplacing an ELSE: an ELSE belongs to the unmatched IF at the same nesting level.
  • Missing ENDIF statements: every opened IF structure must be closed.
  • Poor indentation: unclear indentation makes it difficult to see which statements belong to each branch.
  • Replacing independent IF statements with ELSE: this may prevent a second valid action from running.
  • Including CASE on this page: multi-way value matching belongs to Section 11.2.2.

Practice

Question 1: one-way decision

Write pseudocode that displays "Request maintenance" when ErrorCount is greater than 6. No alternative output is required.

Question 2: two-way decision

Write pseudocode that outputs "Even" when Number MOD 2 = 0 and "Odd" otherwise.

Question 3: trace a boundary

IF EnergyLevel >= 35
THEN
    OUTPUT "Continue"
ELSE
    OUTPUT "Recharge"
ENDIF

State the output for values 34, 35 and 36.

Question 4: nested access decision

A user may open a secure archive only if HasStaffCard is true. When a staff card is present, the algorithm must also check whether HasArchivePermission is true.

Write a nested decision producing these messages:

  • "Archive opened"
  • "Archive permission required"
  • "Staff card required"

Question 5: order of tests

IF ResponseTime < 500
THEN
    OUTPUT "Acceptable"
ELSE
    IF ResponseTime < 200
    THEN
        OUTPUT "Fast"
    ELSE
        OUTPUT "Slow"
    ENDIF
ENDIF

Explain why the output "Fast" can never be produced. Rewrite the structure so that:

  • below 200 produces "Fast";
  • 200 to below 500 produces "Acceptable";
  • 500 or above produces "Slow".

Question 6: independent or exclusive?

A learner earns one badge for completing a project and another badge for attending a presentation. Both badges may be awarded.

Explain why two independent IF statements are more suitable than IF...ELSE.

Question 7: trace a nested decision

IF IsNetworkAvailable = TRUE
THEN
    IF IsUserAuthenticated = TRUE
    THEN
        OUTPUT "Synchronise files"
    ELSE
        OUTPUT "Sign in required"
    ENDIF
ELSE
    OUTPUT "Work offline"
ENDIF

State the output and conditions evaluated for:

  1. IsNetworkAvailable = FALSE, IsUserAuthenticated = TRUE
  2. IsNetworkAvailable = TRUE, IsUserAuthenticated = FALSE
  3. IsNetworkAvailable = TRUE, IsUserAuthenticated = TRUE
Show suggested answers

Question 1

IF ErrorCount > 6
THEN
    OUTPUT "Request maintenance"
ENDIF

Question 2

IF Number MOD 2 = 0
THEN
    OUTPUT "Even"
ELSE
    OUTPUT "Odd"
ENDIF

Question 3

  • 34 produces "Recharge".
  • 35 produces "Continue".
  • 36 produces "Continue".

Question 4

IF HasStaffCard = TRUE
THEN
    IF HasArchivePermission = TRUE
    THEN
        OUTPUT "Archive opened"
    ELSE
        OUTPUT "Archive permission required"
    ENDIF
ELSE
    OUTPUT "Staff card required"
ENDIF

Question 5

Every value below 200 is also below 500, so the first condition captures it before the inner test is reached.

IF ResponseTime < 200
THEN
    OUTPUT "Fast"
ELSE
    IF ResponseTime < 500
    THEN
        OUTPUT "Acceptable"
    ELSE
        OUTPUT "Slow"
    ENDIF
ENDIF

Question 6

The conditions are independent and both rewards may be earned. IF...ELSE would make the two outcomes mutually exclusive.

IF ProjectComplete = TRUE
THEN
    OUTPUT "Award project badge"
ENDIF

IF AttendedPresentation = TRUE
THEN
    OUTPUT "Award presentation badge"
ENDIF

Question 7

  1. Output: "Work offline". Only the network condition is evaluated.
  2. Output: "Sign in required". Both conditions are evaluated.
  3. Output: "Synchronise files". Both conditions are evaluated.

Review

Construct Use it when... Key behaviour
One-way IF An action is required only when a condition is true The block may be skipped
IF...ELSE Exactly two alternatives are required Exactly one branch executes
Nested IF A second decision depends on the path through an earlier decision Some inner conditions may not be evaluated
Independent IF statements Several conditions must be checked separately More than one action may execute
Final exam tip: identify every condition, evaluate only the conditions reached, name the branch followed and record the exact statement or output produced.