Task 3 of 7 · 0 solved · 7 to go0%
You can read the problem, but answers are checked only for signed-in students. Sign in to answer →

2.2 Selection — order of the conditions

Lesson

Order matters

Because the first true condition wins, the order of the branches changes the result. For overlapping ranges, put the most specific / strictest condition first, or a looser one will catch a value it shouldn't.


Worked example

// correct: strict first
if (s >= 90) grade = "A";
else if (s >= 80) grade = "B";

// wrong order: 95 would match >= 80 first and become "B"
if (s >= 80) grade = "B";
else if (s >= 90) grade = "A";   // never reached for 95

▶ Try it: these branches are in the wrong order. Run it — 95 prints B, not A. Now swap the two branches so s >= 90 is checked first, and run again — now it prints A.



In the wrong-order version above, what grade does s = 95 get?


For if (mph < 30) "slow"; else if (mph <= 60) "ok"; else "fast";, what does mph = 30 give?


For the same speed chain, type what mph = 75 gives:


True or false?


Put these branches in the correct order so each score gets the right grade (strictest first).