Topic 8 · Programming
Selection with IF and CASE
Make decisions with IF, ELSE, nested IF statements, and CASE OF, using comparison and Boolean operators.
IF ... THEN ... ELSE
Selection lets a program choose which statements to run. An IF statement checks a condition. If it is TRUE, the THEN block runs. If it is FALSE, the optional ELSE block runs instead.
DECLARE Mark : INTEGER
INPUT Mark
IF Mark >= 50
THEN
OUTPUT "Pass"
ELSE
OUTPUT "Try again"
ENDIF| Mark | Mark >= 50 | OUTPUT |
|---|---|---|
| 72 | TRUE | Pass |
| 50 | TRUE | Pass |
| 49 | FALSE | Try again |
| 0 | FALSE | Try again |
>= includes it, > would not.Comparison operators
Conditions are built from comparisons, which always give TRUE or FALSE:
| Operator | Meaning | Example that is TRUE |
|---|---|---|
= | equal to | 5 = 5 |
<> | not equal to | 5 <> 3 |
< | less than | 3 < 5 |
<= | less than or equal to | 5 <= 5 |
> | greater than | 7 > 2 |
>= | greater than or equal to | 7 >= 7 |
AND, OR, NOT
Boolean operators combine conditions. AND is TRUE only if both sides are TRUE. OR is TRUE if at least one side is TRUE. NOT flips TRUE and FALSE.
DECLARE Age : INTEGER
DECLARE Ticket : STRING
INPUT Age
INPUT Ticket
IF Age >= 12 AND Ticket = "Y"
THEN
OUTPUT "Enjoy the film"
ELSE
OUTPUT "Sorry, you cannot go in"
ENDIFNested IF
An IF can sit inside the THEN or ELSE block of another IF. The inner condition is only checked when the program reaches the branch that contains it: here, only when Mark >= 70 is FALSE. Indent each level so you can see which ENDIF closes which IF.
DECLARE Mark : INTEGER
INPUT Mark
IF Mark >= 70
THEN
OUTPUT "Grade A"
ELSE
IF Mark >= 50
THEN
OUTPUT "Grade B"
ELSE
OUTPUT "Grade C"
ENDIF
ENDIFCASE OF
When one variable is compared against several fixed values, CASE OF is shorter and clearer than many nested IFs. OTHERWISE catches every value not listed.
DECLARE Choice : INTEGER
OUTPUT "1 Play 2 Settings 3 Quit"
INPUT Choice
CASE OF Choice
1 : OUTPUT "Starting game"
2 : OUTPUT "Opening settings"
3 : OUTPUT "Goodbye"
OTHERWISE : OUTPUT "Invalid choice"
ENDCASEKey terms
- Selection
- Choosing which statements to run based on a condition.
- Condition
- An expression that evaluates to TRUE or FALSE.
- Nested statement
- A selection or loop placed inside another one.
- CASE
- Selection that compares one value against a list of options.
Check yourself
What is output when Mark is 50 in the nested IF example?Show answer
Grade B. The first test (>= 70) is FALSE, the second (>= 50) is TRUE.
Is NOT (5 > 3) OR 2 = 2 TRUE or FALSE?Show answer
NOT TRUE is FALSE, 2 = 2 is TRUE, and FALSE OR TRUE is TRUE.
When is CASE a better choice than IF?Show answer
When a single variable is compared against several specific values, such as a menu choice.
Practise this skill
Use what you learned in a question, then run your answer in the studio editor.