Selection — the Case Structure
The CASE structure (called switch in C and Java, match in modern Python)
selects one of many branches by comparing a single expression against a list of
values.
The form
CASE expression OF
value1 : statements A
value2 : statements B
value3 : statements C
OTHERWISE : statements D
ENDCASE
The expression is evaluated once, then matched against each value. OTHERWISE
(sometimes DEFAULT) catches anything unmatched.
Example
BEGIN
READ day
CASE day OF
1 : PRINT "Monday"
2 : PRINT "Tuesday"
3 : PRINT "Wednesday"
4 : PRINT "Thursday"
5 : PRINT "Friday"
6 : PRINT "Saturday"
7 : PRINT "Sunday"
OTHERWISE : PRINT "Invalid day number"
ENDCASE
END
The equivalent IF-ELSE chain needs seven conditions, each repeating day =.
The CASE version states the variable once.
CASE versus IF-ELSE
| CASE | IF-ELSE chain | |
|---|---|---|
| Tests | One expression against several values | Any conditions, unrelated if you like |
| Ranges | Awkward — needs a trick | Natural |
| Complex conditions | No | Yes |
| Readability with many branches | Better | Degrades quickly |
| Speed | Often faster (jump table) | Sequential tests |
Use CASE when: one variable is compared against a set of discrete values.
Use IF-ELSE when: conditions involve ranges, multiple variables, or compound logic.
Handling ranges in a CASE
CASE matches exact values, so a range like "60 to 64" doesn't fit directly. The standard trick is to reduce the range to a single value first:
band ← marks DIV 10 integer division
CASE band OF
10, 9 : grade ← "S"
8 : grade ← "A"
7 : grade ← "B"
OTHERWISE : grade ← "F"
ENDCASE
marks DIV 10 maps 0–9 to 0, 10–19 to 1, and so on — turning a range into a
value CASE can match. Note this only works when the boundaries fall on multiples
of ten, which is exactly why the KTU grade scale (with its 85 and 55 cut-offs)
does not fit a case structure neatly. More on that in the grade-scale topic.
The fall-through warning
In C and Java, a case without break falls through to the next one — a
notorious source of bugs. Pseudocode CASE does not fall through: each branch
ends by itself. If you later write C, remember the difference.