CIE AS & A Level Computer Science, section 11.2 (Constructs)
IF statement
IF Mark >= 50 THEN
OUTPUT "Pass"
ENDIF
With an ELSE clause:
IF Mark >= 50 THEN
OUTPUT "Pass"
ELSE
OUTPUT "Fail"
ENDIF
Nested IF
An IF inside another IF chooses between several outcomes.
IF Mark >= 70 THEN
Grade ← "A"
ELSE
IF Mark >= 60 THEN
Grade ← "B"
ELSE
IF Mark >= 50 THEN
Grade ← "C"
ELSE
Grade ← "U"
ENDIF
ENDIF
ENDIF
CASE structure
A CASE chooses between several fixed values of one variable, and is clearer than many IFs.
CASE OF Choice
1 : OUTPUT "Start"
2 : OUTPUT "Options"
3 : OUTPUT "Quit"
OTHERWISE : OUTPUT "Invalid choice"
ENDCASE
Python
mark = 64
if mark >= 70:
grade = "A"
elif mark >= 60:
grade = "B"
elif mark >= 50:
grade = "C"
else:
grade = "U"
print(grade) # B
Choosing
IF ... ELSEfor a two-way decision.- Nested
IFfor decisions with ranges of values. CASEfor a menu or a single value with many options.
Common mistake: checking conditions in the wrong order. In a nested set of tests for ranges, check the highest boundary first, otherwise every mark above 50 would get a C. Also, close every IF with its own ENDIF.
Exam tip: indent the statements inside each branch, make sure each IF has an ENDIF, and test with a value on each boundary (for example 50 and 49).
Check yourself
When is a CASE structure better than nested IF statements?
When one variable is compared with several fixed values, such as menu options.
What keyword ends an IF statement?
ENDIF.
What is the purpose of OTHERWISE in a CASE?
It gives the action to take when none of the listed values matches.