A-Level Computer Science / Unit 11: Structured Programming

11.2.2 Selecting from Several Alternatives with CASE

πŸ”’ Lesson slides are available to signed-in users. Sign in

11.2.2 Selecting from Several Alternatives with CASE

A CASE structure selects one path by comparing a controlling expression with a collection of possible values or ranges.

It is particularly useful when the same identifier must be checked against several clearly defined alternatives. It can make such decisions easier to read than a long series of nested IF statements.

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

  • Explain how a CASE structure controls program flow.
  • Write correctly structured CASE pseudocode.
  • Match a selector against individual values.
  • Group several values so that they share one branch.
  • Use inclusive numeric ranges as case labels.
  • Use OTHERWISE to handle unmatched values.
  • Trace which branch executes for a supplied selector value.
  • Choose between CASE and IF for a given problem.
  • Identify overlapping, missing or unreachable case alternatives.
Connection to 11.2.1: an IF can test any Boolean expression. A CASE is more specialised: one controlling value is matched against listed alternatives.

What Does a CASE Structure Do?

A CASE structure evaluates one expression, called the selector. Its value is compared with the labels written inside the structure.

Selector: the expression whose value determines which CASE branch is executed.
Case label: a value, group of values or range associated with one branch.
Stage What happens
Evaluate the selector The controlling expression produces one value
Search the labels The value is compared with the listed alternatives
Select a branch The statements belonging to the matching label execute
Handle no match The OTHERWISE branch runs when one is present
Continue Execution resumes after ENDCASE
Common misconception: a CASE structure does not evaluate a different Boolean expression for every branch. It evaluates one selector and matches its result against the case labels.

The General CASE Structure

CASE OF <Selector>
    <Value1> : <Statement or statements>
    <Value2> : <Statement or statements>
    OTHERWISE <Statement or statements>
ENDCASE
Part Purpose
CASE OF Begins the structure and identifies the selector
Case label States which selector value or values use that branch
Colon Separates a label from its statements
OTHERWISE Provides a branch for values that match no listed label
ENDCASE Marks the end of the complete structure
Indent every branch consistently. Clear indentation makes the relationship between each label and its statements easy to follow.

Matching Individual Values

Each branch may represent one exact selector value.

Original example: delivery method

CASE OF DeliveryMode
    'B' : OUTPUT "Use a bicycle courier"
    'D' : OUTPUT "Dispatch a drone"
    'R' : OUTPUT "Use a road vehicle"
    OTHERWISE OUTPUT "Unknown delivery mode"
ENDCASE
DeliveryMode Matching label Output
'B' 'B' Use a bicycle courier
'D' 'D' Dispatch a drone
'R' 'R' Use a road vehicle
'X' No listed value Unknown delivery mode
Common mistake: do not repeat the selector inside each label. Write 'B' :, not DeliveryMode = 'B' :.

Grouping Values That Share an Action

Several individual selector values may be listed together when they should execute the same statements.

Original example: laboratory zones

CASE OF ZoneCode
    'A', 'B' : AccessMessage ← "Standard access"
    'C', 'D' : AccessMessage ← "Supervised access"
    'X'      : AccessMessage ← "Restricted area"
    OTHERWISE AccessMessage ← "Invalid zone"
ENDCASE

OUTPUT AccessMessage
Selector value Matched group Stored message
'A' 'A', 'B' Standard access
'B' 'A', 'B' Standard access
'D' 'C', 'D' Supervised access
'X' 'X' Restricted area

Grouping the values avoids repeating the same assignment in several separate branches.

Group values only when they genuinely require identical processing.

Using Numeric Ranges

A branch may also cover a continuous range of values using TO. Both endpoints of the range are included.

Original example: sensor score

CASE OF SensorScore
    0 TO 29   : OUTPUT "Recalibrate now"
    30 TO 59  : OUTPUT "Monitor closely"
    60 TO 84  : OUTPUT "Operating normally"
    85 TO 100 : OUTPUT "High sensitivity"
    OTHERWISE OUTPUT "Invalid sensor score"
ENDCASE
SensorScore Matching range Output
0 0 TO 29 Recalibrate now
29 0 TO 29 Recalibrate now
30 30 TO 59 Monitor closely
84 60 TO 84 Operating normally
101 No listed range Invalid sensor score
Common mistake: avoid gaps and overlaps unless they are deliberately required. For example, the ranges 0 TO 30 and 30 TO 60 both contain 30.

Handling Unmatched Values with OTHERWISE

OTHERWISE provides a fallback branch. It runs when the selector matches none of the listed values or ranges.

CASE OF OperationCode
    1 : OUTPUT "Start"
    2 : OUTPUT "Pause"
    3 : OUTPUT "Stop"
    OTHERWISE OUTPUT "Invalid operation code"
ENDCASE
Fallback branch: a branch used when no earlier alternative matches the supplied value.

Why include OTHERWISE?

Reason Benefit
Unexpected input The user receives a meaningful response
Invalid stored data The algorithm can identify an impossible or unsupported value
Future changes New or unrecognised codes do not silently produce no action
Testing The unmatched path can be checked deliberately

OTHERWISE is optional. Without it, a selector that matches no case causes no branch to run, and execution continues after ENDCASE.

Include OTHERWISE when invalid or unexpected values need a defined response.

Only One CASE Branch Should Execute

The selector is evaluated once. The matching branch executes, and execution then continues after ENDCASE.

CASE OF AlertCode
    1 : AlertMessage ← "Information"
    2 : AlertMessage ← "Warning"
    3 : AlertMessage ← "Critical"
    OTHERWISE AlertMessage ← "Unknown"
ENDCASE

OUTPUT AlertMessage

When AlertCode is 2, only the assignment associated with 2 is performed. The algorithm does not continue through the labels for 3 or OTHERWISE.

No fall-through: do not assume that execution automatically continues into the next case branch. Each label represents an alternative path.

Labels should not overlap

CASE OF Reading
    0 TO 50   : OUTPUT "First range"
    40 TO 100 : OUTPUT "Second range"
ENDCASE

Values from 40 to 50 match both labels. This creates ambiguity and should be avoided by defining non-overlapping alternatives.

Choosing Between CASE and IF

Situation More suitable construct Reason
One menu number is matched with several commands CASE One selector is compared with fixed values
One letter code selects a processing mode CASE Each exact value has a clear branch
One score is divided into non-overlapping bands CASE The selector is matched against ranges
Access requires a card and a correct password IF The decision uses a compound Boolean condition
Temperature is high or pressure is unsafe IF Different identifiers are involved
Several unrelated tests must run independently Separate IF statements More than one action may be required

Suitable CASE design

CASE OF PrintMode
    1 : OUTPUT "Draft"
    2 : OUTPUT "Standard"
    3 : OUTPUT "High quality"
    OTHERWISE OUTPUT "Invalid mode"
ENDCASE

More suitable as IF

IF IsLoggedIn = TRUE AND HasPrintCredit = TRUE
THEN
    OUTPUT "Print request accepted"
ELSE
    OUTPUT "Print request rejected"
ENDIF
A strong justification identifies whether the decision is based on one selector matched against alternatives or on a more general Boolean condition.

A Reliable Method for Tracing CASE

Stage Action Question to ask
1. Evaluate Find the current value of the selector What exact value is being matched?
2. Inspect Compare the selector with each label or range Which branch contains this value?
3. Select Enter the matching branch Which statements belong to it?
4. Execute Perform only the selected branch’s statements What values or outputs change?
5. Continue Move to the statement after ENDCASE Is there a shared statement after the structure?
During a trace, write the selector value, the matched label and the resulting statement or output. Do not merely state that β€œthe CASE runs”.

Worked Example: Equipment Inspection Result

A workshop records an inspection score from 0 to 100. The algorithm stores a category and a required action.

Pseudocode

DECLARE InspectionScore : INTEGER
DECLARE ConditionCategory : STRING
DECLARE RequiredAction : STRING

OUTPUT "Enter the inspection score: "
INPUT InspectionScore

CASE OF InspectionScore
    0 TO 34 :
        ConditionCategory ← "Unsafe"
        RequiredAction ← "Remove from service"

    35 TO 64 :
        ConditionCategory ← "Needs attention"
        RequiredAction ← "Schedule maintenance"

    65 TO 84 :
        ConditionCategory ← "Serviceable"
        RequiredAction ← "Continue monitoring"

    85 TO 100 :
        ConditionCategory ← "Excellent"
        RequiredAction ← "Return to normal use"

    OTHERWISE
        ConditionCategory ← "Invalid"
        RequiredAction ← "Check the entered score"
ENDCASE

OUTPUT "Category: ", ConditionCategory
OUTPUT "Action: ", RequiredAction

Trace using InspectionScore = 78

Stage Result
Selector value 78
Matched label 65 TO 84
ConditionCategory "Serviceable"
RequiredAction "Continue monitoring"
Final outputs Category: Serviceable
Action: Continue monitoring

Boundary checks

Score Matched label Category
34 0 TO 34 Unsafe
35 35 TO 64 Needs attention
84 65 TO 84 Serviceable
85 85 TO 100 Excellent
108 OTHERWISE Invalid
When branches use ranges, test both endpoints of every range as well as values immediately before and after each boundary.

Interactive: CASE Router

Choose a CASE pattern, change the selector and trace the branch that executes. The visualiser distinguishes exact labels, grouped labels, ranges and the OTHERWISE path.

Each supported letter has its own CASE label.

Matched case 'D'

The selector contains 'D', so the branch labelled 'D' executes.

Result: Dispatch a drone
During the animation, observe that the selector is evaluated once and only the matched branch is highlighted.

Common Mistakes and Misconceptions

  • Writing conditions as labels: use 'A' :, not Code = 'A' :.
  • Testing different identifiers: one CASE structure should use one controlling selector.
  • Using CASE for complex Boolean conditions: use IF when conditions involve several variables or logical operators.
  • Overlapping labels: avoid ranges or groups that can match the same value.
  • Leaving gaps accidentally: check that every valid selector value is represented.
  • Forgetting OTHERWISE: an unexpected value may otherwise produce no defined response.
  • Assuming every branch executes: only the matching branch runs.
  • Assuming fall-through: execution does not continue through subsequent case labels.
  • Forgetting ENDCASE: the structure must be closed clearly.
  • Repeating identical branches: group values when they require the same action.
  • Incorrect range boundaries: remember that both endpoints in Lower TO Upper are included.

Practice

Question 1: individual values

Write a CASE structure for MachineMode:

  • 'A' outputs "Automatic";
  • 'M' outputs "Manual";
  • 'S' outputs "Standby";
  • any other value outputs "Invalid mode".

Question 2: grouped values

Write a CASE structure for DayCode:

  • 'M', 'T', 'W' and 'H' output "Core timetable";
  • 'F' outputs "Project timetable";
  • 'S' and 'U' output "Weekend timetable";
  • other values output "Invalid day code".

Question 3: ranges

Write a CASE structure that categorises SignalQuality as:

  • 0 to 19: "Very weak";
  • 20 to 49: "Weak";
  • 50 to 79: "Stable";
  • 80 to 100: "Strong";
  • anything else: "Invalid quality value".

Question 4: trace a CASE structure

CASE OF PriorityCode
    1, 2 : OUTPUT "Routine"
    3    : OUTPUT "Urgent"
    4, 5 : OUTPUT "Critical"
    OTHERWISE OUTPUT "Invalid priority"
ENDCASE

State the output for selector values 2, 3, 5 and 8.

Question 5: find the overlap

CASE OF Reading
    0 TO 25  : OUTPUT "Low"
    25 TO 60 : OUTPUT "Medium"
    61 TO 90 : OUTPUT "High"
ENDCASE

Identify the ambiguous value and correct the ranges.

Question 6: CASE or IF?

Choose the more suitable construct and justify your answer:

  1. A menu number from 1 to 6 selects one command.
  2. Access is granted when a user is authenticated and has administrator permission.
  3. A grade letter is matched with one of several feedback messages.
  4. A warning is displayed when temperature is high or pressure is low.

Question 7: complete the missing branch

CASE OF CommandCode
    'N' : OUTPUT "Create new record"
    'E' : OUTPUT "Edit record"
    'D' : OUTPUT "Delete record"
    ______________________________
ENDCASE

Add a suitable fallback response.

Question 8: reduce repetition

CASE OF DeviceCode
    'P' : DeviceGroup ← "Portable"
    'T' : DeviceGroup ← "Portable"
    'L' : DeviceGroup ← "Portable"
    'D' : DeviceGroup ← "Desktop"
    OTHERWISE DeviceGroup ← "Unknown"
ENDCASE

Rewrite the CASE structure by grouping labels that share an assignment.

Show suggested answers

Question 1

CASE OF MachineMode
    'A' : OUTPUT "Automatic"
    'M' : OUTPUT "Manual"
    'S' : OUTPUT "Standby"
    OTHERWISE OUTPUT "Invalid mode"
ENDCASE

Question 2

CASE OF DayCode
    'M', 'T', 'W', 'H' : OUTPUT "Core timetable"
    'F'                 : OUTPUT "Project timetable"
    'S', 'U'            : OUTPUT "Weekend timetable"
    OTHERWISE OUTPUT "Invalid day code"
ENDCASE

Question 3

CASE OF SignalQuality
    0 TO 19   : OUTPUT "Very weak"
    20 TO 49  : OUTPUT "Weak"
    50 TO 79  : OUTPUT "Stable"
    80 TO 100 : OUTPUT "Strong"
    OTHERWISE OUTPUT "Invalid quality value"
ENDCASE

Question 4

  • 2 produces "Routine".
  • 3 produces "Urgent".
  • 5 produces "Critical".
  • 8 produces "Invalid priority".

Question 5

The value 25 appears in both of the first two ranges. One correction is:

CASE OF Reading
    0 TO 24  : OUTPUT "Low"
    25 TO 60 : OUTPUT "Medium"
    61 TO 90 : OUTPUT "High"
    OTHERWISE OUTPUT "Invalid reading"
ENDCASE

Question 6

  1. CASE: one menu selector is matched against several fixed values.
  2. IF: the decision uses two Boolean conditions joined by AND.
  3. CASE: one grade selector is matched against letter values.
  4. IF: the condition uses different identifiers joined by OR.

Question 7

OTHERWISE OUTPUT "Invalid command code"

Question 8

CASE OF DeviceCode
    'P', 'T', 'L' : DeviceGroup ← "Portable"
    'D'           : DeviceGroup ← "Desktop"
    OTHERWISE DeviceGroup ← "Unknown"
ENDCASE

Review

Feature Key idea Example
Selector The value used to choose a branch CASE OF MenuChoice
Single label Matches one exact value 'D' :
Grouped labels Several values share one branch 'A', 'B' :
Range Matches every value between inclusive endpoints 20 TO 49 :
OTHERWISE Handles values that match no listed label OTHERWISE OUTPUT "Invalid"
ENDCASE Closes the complete structure Execution continues afterward
Final exam tip: state the selector value, identify the exact label or range it matches, execute only that branch, and then continue after ENDCASE.