Selection is a programming construct that allows a program to execute different code depending on whether a condition is true or false. This is how programs make decisions.
The simplest form of selection. If the condition is TRUE, the first block runs. If FALSE, the ELSE block runs (optional).
IF condition THEN
// code to run if condition is TRUE
ENDIF
IF score >= 50 THEN
OUTPUT "Pass"
ELSE
OUTPUT "Fail"
ENDIF
IF score >= 70 THEN
OUTPUT "Grade A"
ELSE
IF score >= 50 THEN
OUTPUT "Grade B"
ELSE
OUTPUT "Fail"
ENDIF
ENDIF
IF score >= 70 THEN
OUTPUT "Grade A"
ELSE IF score >= 60 THEN
OUTPUT "Grade B"
ELSE IF score >= 50 THEN
OUTPUT "Grade C"
ELSE
OUTPUT "Fail"
ENDIF
CASE OF is used when you want to select from several discrete options based on the value of a single variable. It's cleaner than a long chain of IF...ELSE IF when you have many options.
CASE OF day
1: OUTPUT "Monday"
2: OUTPUT "Tuesday"
3: OUTPUT "Wednesday"
4: OUTPUT "Thursday"
5: OUTPUT "Friday"
6: OUTPUT "Saturday"
7: OUTPUT "Sunday"
OTHERWISE: OUTPUT "Invalid day"
ENDCASE
CASE OF choice
"A": OUTPUT "Option A selected"
"B": OUTPUT "Option B selected"
"C": OUTPUT "Exit"
OTHERWISE: OUTPUT "Invalid choice"
ENDCASE
| Use IF when... | Use CASE OF when... |
|---|---|
| Testing a range of values (e.g., score >= 50) | Testing for specific exact values |
| Complex boolean conditions (AND/OR) | Selecting from a menu of options |
| Two alternatives only | Many discrete alternatives |
4 questions · 10 marks
| Term | Definition |
|---|
10 minutes · mixed marks