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
CASEstructure 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
OTHERWISEto handle unmatched values. - Trace which branch executes for a supplied selector value.
- Choose between
CASEandIFfor a given problem. - Identify overlapping, missing or unreachable case alternatives.
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.
| 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 |
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 |
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 |
'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.
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 |
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
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.
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.
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 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? |
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 |
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.
Common Mistakes and Misconceptions
-
Writing conditions as labels: use
'A' :, notCode = 'A' :. - Testing different identifiers: one CASE structure should use one controlling selector.
-
Using CASE for complex Boolean conditions: use
IFwhen 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 Upperare 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:
- A menu number from 1 to 6 selects one command.
- Access is granted when a user is authenticated and has administrator permission.
- A grade letter is matched with one of several feedback messages.
- 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
2produces"Routine".3produces"Urgent".5produces"Critical".8produces"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
-
CASE: one menu selector is matched against several fixed values. -
IF: the decision uses two Boolean conditions joined byAND. -
CASE: one grade selector is matched against letter values. -
IF: the condition uses different identifiers joined byOR.
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 |
ENDCASE.