Unable to open this exercise
Common exam pitfall
Students often miss the OTHERWISE default branch when the input does not match any specified list.
When an algorithm must branch across many mutually exclusive outcomes based on the value of a single variable, nesting dozens of IF ... THEN ... ELSE statements creates messy, hard-to-read code. Cambridge pseudocode provides the CASE OF statement for elegant multi-way branching.
1. Syntax of CASE OF
CASE OF <Identifier>
<Value1> : <Statement>
<Value2> : <Statement>
<LowValue> TO <HighValue> : <Statement>
<ValA>, <ValB>, <ValC> : <Statement>
OTHERWISE : <Statement>
ENDCASE
Key Syntax Rules:
- Target Variable: Specified once in the
CASE OF <Identifier>header. - Selector Colons: Each matching value is followed immediately by a colon
:. - Range Support: You can test inclusive ranges using the keyword
TO(e.g.1 TO 10 : ...). - List Support: You can test comma-separated discrete values (e.g.
'A', 'E', 'I', 'O', 'U' : ...). - Fallback (
OTHERWISE): Catches any input value that did not match any of the prior branches. - Closing (
ENDCASE): Required to terminate the structure.
2. Comparison: Nested IF vs CASE OF
Feature | Nested |
|
|---|---|---|
Best Used For | Complex conditions involving multiple variables, relational operators ( | Inspecting a single variable against specific constants or discrete ranges. |
Readability | Tends to drift rightwards with deep indentation ("pyramid of doom"). | Clean vertical alignment of branches. |
Default Handling | Final |
|
Termination Keyword | Multiple | Single |
AI Socratic Tutor
Need guidance? Ask a question or use the hint below.
AI Socratic Tutor is an All-Access Benefit
Unlock step-by-step Socratic hints, algorithm trace table walkthroughs, and error diagnostics for every Cambridge exercise.
You're chatting with an AI tutor, not a person. AI can make mistakes, so double-check its answers.
Exam-Style Question: Trace CASE OF Evaluation
Task
Trace the execution of this CASE OF construct:
CASE OF DayNumber
1, 2, 3, 4, 5 : Status <- "Weekday"
6, 7 : Status <- "Weekend"
OTHERWISE : Status <- "Invalid"
ENDCASE
OUTPUT "Status: ", Status
Trace the output for three test values: DayNumber = 3, DayNumber = 7, and DayNumber = 9. Complete the trace table rows.
| # | DayNumber | Status | OUTPUT |
|---|---|---|---|
| 1 | |||
| 2 | |||
| 3 |
Interactive exercises for Module 2 and beyond require an active plan.