KTU S1

Selection — the Case Structure

By the end you should be able to: Write pseudocode using the CASE structure, and judge when a case structure is preferable to a chain of if-else statements.

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

CASEIF-ELSE chain
TestsOne expression against several valuesAny conditions, unrelated if you like
RangesAwkward — needs a trickNatural
Complex conditionsNoYes
Readability with many branchesBetterDegrades quickly
SpeedOften 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.