Published by Patrick Mutisya · 14 days ago
In this section you will learn how to use the CASE (also called switch) construct in pseudocode. The CASE structure provides a clear way to select one of many alternatives based on the value of a single expression.
| Component | Pseudocode |
|---|---|
| Start of CASE | CASE expression OF |
| First option | value1 : statements |
| Additional options | value2 : statements |
| Default option | OTHERWISE : statements |
| End of CASE | END CASE |
All statements belonging to a particular option are indented beneath the colon. The OTHERWISE clause is optional but recommended to handle unexpected values.
CASE expression OF on a new line.OTHERWISE clause for any values not explicitly listed.END CASE.Suppose we have a variable mark that contains a student's exam mark (0–100). We want to assign a letter grade according to the following rules:
Because the ranges are not single values, we first convert the mark to a “grade band” using integer division, then apply a CASE structure.
READ mark
SET band ← mark DI \cdot 10 // integer division
CASE band OF
10 : grade ← 'A' // mark = 100
9 : grade ← 'A' // 90–99
8 : grade ← 'B' // 80–89
7 : grade ← 'C' // 70–79
6 : grade ← 'D' // 60–69
OTHERWISE : grade ← 'F' // 0–59
END CASE
WRITE grade
Note the use of DIV to obtain the tens digit, which makes the CASE values simple integers.
| Aspect | IF…ELSE IF…ELSE | CASE |
|---|---|---|
| Decision basis | Multiple independent Boolean expressions | Single expression compared to constant values |
| Readability | Can become lengthy with many conditions | Compact when many discrete values are possible |
| Evaluation | Each condition evaluated until one is true | Expression evaluated once; then a lookup |
| Default handling | ELSE clause | OTHERWISE clause |
END CASE – leads to ambiguous block termination.>=) inside a CASE – CASE only matches exact values.OTHERWISE clause when an unexpected value could occur.Write pseudocode using a CASE structure to determine the number of days in a month. The variable month holds an integer from 1 (January) to 12 (December). Assume February always has 28 days.
month.days.days.Suggested solution (try to write it yourself first):
READ month
CASE month OF
1 : days ← 31
2 : days ← 28
3 : days ← 31
4 : days ← 30
5 : days ← 31
6 : days ← 30
7 : days ← 31
8 : days ← 31
9 : days ← 30
10 : days ← 31
11 : days ← 30
12 : days ← 31
OTHERWISE : days ← -1 // invalid month
END CASE
WRITE days
OTHERWISE clause to make your pseudocode robust.END CASE.