Recap
- A nested conditional is a conditional inside the block of another.
- The outer condition is evaluated first. The inner one is evaluated only when control enters its block.
- An ELSE pairs with the IF whose block closes just before it (follow the braces).
- In a chain of ranges each test is inside the previous ELSE, so conditions can be simple, but order matters.
IF(a) { IF(b) { X } }with no ELSE blocks is equivalent toIF(a AND b) { X }.
Key relationships
| Structure | Paths | Test values needed |
|---|---|---|
| IF(a) { IF(b) {X} } | X runs, or nothing | a true and b true; a true and b false; a false |
| IF(a) { IF(b) {X} ELSE {Y} } ELSE {Z} | 3 outcomes | One test for each of X, Y and Z |
| Chain: IF(≥ 80) ELSE { IF(≥ 60) ELSE } | 3 outcomes | 90, 70, 50 plus boundaries 80, 60 and 59 |
| Leap year | 4 paths | 2023, 2024, 1900, 2000 |
| Flattened leap year | (year MOD 4 = 0 AND year MOD 100 ≠ 0) OR year MOD 400 = 0 |
Agrees with the nested version |
Assumptions
- Conditions are evaluated top to bottom, outside in.
- Only blocks selected by the conditions run.
- Braces (not layout) show structure.
Method for tracing
- Substitute the input values.
- Evaluate the outer condition and record true or false.
- Enter the correct block. If it holds another IF, evaluate that condition next.
- Continue until a block with no further IF runs. Write the result.
- Repeat for each input you were given.
Mistakes to avoid
- Evaluating the inner IF when the outer test failed.
- Pairing an ELSE with the wrong IF.
- Putting overlapping range tests in the wrong order.
- Testing only one or two of the three outcomes.
- Flattening nesting that has distinct ELSE results.
Worked mini-example
x ← 8
y ← 3
IF(x > 5)
{
IF(y > 5)
{
DISPLAY("P")
}
ELSE
{
DISPLAY("Q")
}
}
ELSE
{
DISPLAY("R")
}
Output: Q
x > 5 is true, so the first block is entered. Then y > 5 is false, so the inner ELSE runs and Q is displayed. R is displayed only when x is not greater than 5.
Quick self-check
- In the example above, what is displayed if
xis 2 andyis 9? - Why does
IF(score ≥ 60)beforeIF(score ≥ 80)give the wrong grade to 90? - Rewrite
IF(a) { IF(b) { DISPLAY("ok") } }as one IF.
Answers
R: the outer condition is false, so the inner IF is never evaluated.- 90 satisfies
≥ 60first and gets the lower grade; the≥ 80test is never reached. IF(a AND b) { DISPLAY("ok") }.
Where marks are won and lost
Expect tracing questions with two inputs, where the code asks a second question depending on the first. Another favourite is a chain of ranges with the tests in a different order, asking what a given input receives. Questions about equivalent code ask whether a nested conditional and a Boolean expression always agree. Choose test inputs for each path and check each boundary value. Draw the braces if the layout confuses you.
Back to the full study guide for worked examples and explanations.