Unit 4 · Thinking like a programmer
Why the order of if / else if checks matters
An if / else if chain stops at the first check that is true. Put the narrowest check first: a 3-year-old is also under 18, so age < 5 must come before age < 18. The final else catches everyone left.
The mix-up
What people often think
“The order of the checks does not matter.”
What the tutor says
A 3-year-old is also under 18, so the under-18 check would catch them first and charge 8. Put the narrowest check first.
Walk a 3-year-old through your order. Which question says yes first?
How it works
Walk one case through your order. If an under-18 check comes first, a toddler gets the child price before the free-for-under-5 rule is ever asked.
A branch that never runs is usually in the wrong place, not wrong. Move it up rather than deleting it, and keep the boundary numbers as the rule says.
Side by side
if (age < 18) price = 8;
else if (age < 5) price = 0; // never reached
else price = 14;if (age < 5) price = 0;
else if (age < 18) price = 8;
else price = 14;Close cousins of this mix-up
The tutor watches for these in the same lesson.
“The otherwise step can go anywhere.”
"Otherwise" catches everyone not handled yet. Any check after it never gets a turn, so it goes last.
“If a branch never runs, it can be deleted.”
The Merit rule is still needed. It is not wrong, just in the wrong place. Move it above the Pass check.
“Nudging the numbers is enough.”
Check the edges: 80 should be Merit and 50 should be Pass. Keep >= 80 and >= 50, and change the order instead.
Practise it with a tutor watching
Conditionals: making decisions
Turn a decision into if, else if and else, and put the checks in an order that works.
Free with an account. The first two units need no account.