Unable to open this exercise
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.
Independent Practice: Signal messages
Read RED, AMBER or GREEN. Output STOP, WAIT or GO respectively. Output INVALID for any other string.
Write a complete program. Read inputs in the stated order. Output only the requested results, one per line, without input prompts. Test with your own values before submitting.
Interactive exercises for Module 2 and beyond require an active plan.
Run code to inspect step-by-step variable trace states.