IPA FE Subject B sample Question 2
A question IPA Japan published in 基本情報技術者試験 科目B サンプル問題 問2, translated into English. ITPEC is based on the same exams.
From the answer group below, select the correct combination of answers to be inserted into A through C in the program.
The function fizzBuzz returns “divisible by 3” if the value given as the argument is divisible by 3 and not divisible by 5, “divisible by 5” if it is divisible by 5 and not divisible by 3, and “divisible by 3 and 5” if it is divisible by 3 and 5. In all other cases, it returns “divisible by neither 3 nor 5”.
Answer group
Explanation
A: 3 and 5, B: 3, C: 5 — the branches are tested from the top and only the first true one runs, so the narrowest test, divisible by both 3 and 5, must come first.
A multiple of 15 is divisible by 3 and by 5 as well. If the if tested 3 or 5 first, 15 would stop there and get “divisible by 3” or “divisible by 5”, never “divisible by 3 and 5”. With “3 and 5” tested first, any number that reaches the first elseif is not a multiple of 15, so divisible by 3 there means divisible by 3 and not by 5, and the next test likewise catches the numbers divisible by 5 and not by 3. Everything else falls to else.
Run for num from 1 to 60, only (c) returned the specified string every time: fizzBuzz( gives “divisible by 3 and 5”, fizzBuzz( “divisible by 3”, fizzBuzz( “divisible by 5” and fizzBuzz( “divisible by neither 3 nor 5”.
Answer (c)
Why not others:
- •(a) and (b) — test 3 first, so 15, 30, 45 and every other multiple of 15 return “divisible by 3”, and the “3 and 5” branch is never reached
- •(d) and (e) — test 5 first, so every multiple of 15 returns “divisible by 5”
Key rule: In an if–elseif chain only the first true branch runs, so when one condition implies another, test the narrower one first.
Math & Numbers · AI-written, may contain errors
This question comes from the past questions IPA Japan publishes, translated into English by ITPEC Practice. ITPEC Practice is an independent study tool and is not affiliated with IPA or ITPEC. See the original paper (PDF) or Report an issue.