Nested decisions
This page needs a recent browser (with SharedArrayBuffer support). Please update Chrome, Edge, Firefox or Safari to the latest version.
One speed, three outcomes
- A speed camera: 120 or more loses the licence, 100 or more is a fine, and anything lower is ok.
- One
IFhas two paths. The second decision goes inside theELSE, as its ownIF. - Each
IFhas its ownENDIF. Indent the inner one so you can see whichELSEit belongs to.

DECLARE Speed : INTEGER
Speed ← 105
IF Speed >= 120
THEN
OUTPUT "licence taken"
ELSE
IF Speed >= 100
THEN
OUTPUT "fine"
ELSE
OUTPUT "ok"
ENDIF
ENDIF
Speed |
Speed >= 120 |
Speed >= 100 |
Output |
|---|---|---|---|
| 130 | TRUE |
not tested | licence taken |
| 105 | FALSE |
TRUE |
fine |
| 100 | FALSE |
TRUE |
fine |
| 90 | FALSE |
FALSE |
ok |
- Test the highest boundary first. If
Speed >= 100came first, 130 would get only a fine.
Count the marks that count
- A validation tally walks the array and adds 1 only when the value is in range.
- The range test is the
ANDfrom the previous lesson, inside the loop.
DECLARE Temp : ARRAY[1:5] OF INTEGER
DECLARE Day, Count : INTEGER
Temp[1] ← 21
Temp[2] ← 99
Temp[3] ← -5
Temp[4] ← 18
Temp[5] ← -60
Count ← 0
FOR Day ← 1 TO 5
IF Temp[Day] >= -50 AND Temp[Day] <= 50
THEN
Count ← Count + 1
ELSE
OUTPUT "Day ", Day, " reading rejected"
ENDIF
NEXT Day
OUTPUT Count, " readings accepted"
- A thermometer reading outside -50 to 50 is a fault. The
ELSEreports which day was rejected.
Watch out
- The inner
IFstarts on the line afterELSE. It is not written on theELSEline. - Close the inner
ENDIFbefore the outer one. The lastENDIFbelongs to the firstIF.
Common mistakes
- An
ENDIFin the wrong place closes the outer test and leaves the inner one open. - A speed of exactly 100 is a fine, and exactly 120 loses the licence. The tests use
>=, so check the boundary values.
Now you try
- The first two tasks are a nested grade with boundaries 80 and 50. The third counts the marks from 0 to 100 with
AND. - Press Check answer to test it.
Difficulty 3/5 · 200 coins + a small bonus on first completion today
Read an INTEGER Mark. Output Distinction for 80 or more, otherwise Pass for 50 or more, otherwise Fail. Nest the second IF under ELSE.
Click Run to see the output here.
Difficulty 3/5 · 200 coins + a small bonus on first completion today
Same three outcomes as the previous task. A mark below 50 must reach the inner ELSE; the check also tries marks that must not.
Click Run to see the output here.
Difficulty 3/5 · 200 coins + a small bonus on first completion today
The array Mark holds 80, -1, 100, 40. Count how many values are from 0 to 100 inclusive and output the count (it is 3).
Click Run to see the output here.