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
IFstatement. - Use
IF...ELSEfor two mutually exclusive paths. - Use comparison and logical expressions as conditions.
- Write nested
IFstatements 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.
Selection Changes the Path Through an Algorithm
Without selection, statements normally execute in sequence. A selection construct introduces alternative paths.
| 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 |
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.
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 |
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.
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.
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.
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.
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 |
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? |
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 |
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.
Common Mistakes and Misconceptions
-
Adding a condition after ELSE:
ELSEis already the fallback for a false condition. -
Executing both branches: an
IF...ELSEstructure 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
ELSEbelongs to the unmatchedIFat the same nesting level. -
Missing ENDIF statements: every opened
IFstructure 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:
-
IsNetworkAvailable = FALSE,IsUserAuthenticated = TRUE -
IsNetworkAvailable = TRUE,IsUserAuthenticated = FALSE -
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
34produces"Recharge".35produces"Continue".36produces"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
-
Output:
"Work offline". Only the network condition is evaluated. -
Output:
"Sign in required". Both conditions are evaluated. -
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 |