ITPEC IP April 2024 Question 5
The function calGrade receives the student’s score and returns the grade. The score is an integer. If the score is greater than or equal to 80, the function calGrade returns “A”; if the score is between 65 and 79, it returns “B”; between 50 and 64, it returns “C”; and otherwise, it returns “Fail.” Which of the following is an appropriate piece of code to be inserted in blank in the program?
Explanation
score ≥ 65 — the second test is reached only when the score is below 80, so B needs only its lower bound.
An elseif is tested only when every condition above it was false. Reaching the blank means score ≥ 80 was false, so the score is at most 79, and score ≥ 65 then selects exactly 65 to 79. Checking one score per band:
- •85:
score ≥ 80is true, so "A" - •70: the first test fails and
score ≥ 65is true, so "B" - •55: the first two fail and
score ≥ 50is true, so "C" - •40: every test fails, so "Fail"
Answer (a)
Why not others:
- •(b) —
score ≥ 65 or score ≤ 79is true for every integer, since a score below 65 is also at most 79; every score under 80 gets "B", and "C" and "Fail" are never returned - •(c) — no score is at most 65 and at least 79 at the same time, so the condition is always false: "B" is never returned and 65 to 79 fall through to "C"
- •(d) — every score reaching this test is already at most 79, so
score ≤ 79is always true: 40 would get "B" instead of "Fail"
Key rule: An if/elseif chain is tested top to bottom and the first true branch wins, so each later condition needs only the bound the earlier ones have not already excluded.
Algorithm and Programming · AI-written, may contain errors
This question comes from an official ITPEC past paper. ITPEC Practice is an independent study tool and is not affiliated with ITPEC. See the official IP past-paper collection or Report an issue.