Selection: CASE
CASE OF picks one branch
- A
CASEruns the branch whose value matches the variable. - Branches are tested in order. The first match runs, and the rest are skipped.
OTHERWISEis the branch for every other value. It comes last.
DECLARE Size : CHAR
Size ← 'M'
CASE OF Size
'S' : OUTPUT "small"
'M' : OUTPUT "medium"
'L' : OUTPUT "large"
OTHERWISE : OUTPUT "unknown size"
ENDCASE
A range of values, and longer branches
- In 9618, one clause can cover a range:
<value1> TO <value2> :. Both ends count. - A clause can run several statements. They run until the next value,
OTHERWISEorENDCASE. - The order still matters. If two ranges overlap, only the first one that matches runs.
DECLARE Age, Tickets : INTEGER
Age ← 15
Tickets ← 0
CASE OF Age
0 TO 4 : OUTPUT "Free"
5 TO 17 : OUTPUT "Child ticket"
Tickets ← Tickets + 1
OTHERWISE : OUTPUT "Adult ticket"
Tickets ← Tickets + 1
ENDCASE
OUTPUT "Tickets sold: ", Tickets
The output is Child ticket, then Tickets sold: 1. An age of 5 gives Child ticket, because 5 is an end of that range. A branch can hold more than one statement: here it also adds 1 to Tickets.
Watch out
- A character value uses single quotes:
'M'. - Many short branches read well as a
CASE. Conditions such asMark > 50 AND Absent = FALSEneed anIF. - IGCSE 0478 pseudocode has no ranges and keeps one statement per branch. In 9618 both are allowed.
Common mistakes
- Close the block with
ENDCASE. - Put a colon after the value, and after
OTHERWISE. - Write a range low to high:
5 TO 17, not17 TO 5. A backwards range matches nothing. - Leave no gaps between ranges. With
0 TO 4and6 TO 17, an age of 5 falls toOTHERWISE.
Now you try
- Read a character and choose a word with
CASE OF.
Independent transfer
The final task has no supplied algorithm. Plan its inputs, processing and outputs, then solve it before opening support. Check more than the sample case.
Сложность 1/5 · 100 монет + небольшой бонус за первое завершение сегодня
Read a CHAR Move. Output west for W, east for E, and other for anything else.
Нажмите Запустить, чтобы увидеть результат здесь.
Сложность 2/5 · 140 монет + небольшой бонус за первое завершение сегодня
Read an integer Mark from 0 to 100. Use one CASE with ranges to output A for 70–100, B for 50–69 and U for anything lower.
Нажмите Запустить, чтобы увидеть результат здесь.
Сложность 3/5 · 200 монет + небольшой бонус за первое завершение сегодня
Read integer Rank. Using CASE, output gold for 1, silver for 2, bronze for 3, otherwise unplaced.
Нажмите Запустить, чтобы увидеть результат здесь.