Programming Basics (Pseudocode Tracing)
What does the following function s return when called as s(7)?
○integer: s(integer: n)
if (n ≦ 0)
return 0
endif
return n + s(n − 2)
- A15
- B16
- C28
Show answer and explanation
Answer: B. 16
s(7) calls s(5) to compute 7 + s(5), s(5) calls s(3) for 5 + s(3), s(3) calls s(1) for 3 + s(1), and s(1) calls s(−1) for 1 + s(−1); s(−1) returns 0 because n ≦ 0. The values are added as the calls return, giving s(7) = 7 + 5 + 3 + 1 + 0 = 16. This is the sum of the positive odd numbers up to 7.
- A. This assumes 0 is returned for n ≦ 1, giving 7 + 5 + 3. In fact s(1) returns 1 + s(−1) = 1.
- B. Correct. 7 + 5 + 3 + 1 = 16.
- C. This assumes s(n − 1) is called, giving 7 + 6 + … + 1.
Continue: 9 more Programming Basics (Pseudocode Tracing) questions