Programming Basics (Pseudocode Tracing)
÷ is division; when the result is assigned to an integer variable (including a function argument), the fractional part is discarded. What does the following function f return when called as f(9087)?
○integer: f(integer: x)
integer: s ← 0
while (x > 0)
s ← s + x mod 10
x ← x ÷ 10
endwhile
return s
- A4
- B15
- C24
Show answer and explanation
Answer: C. 24
x mod 10 takes the ones digit of x, and x ← x ÷ 10, which becomes integer division because the fractional part is discarded, removes it. mod has higher precedence than +, so s ← s + x mod 10 means s ← s + (x mod 10). x changes to 9087, 908, 90, 9 and 0, and 7, 8, 0 and 9 are added to s in turn, giving 7 + 8 + 0 + 9 = 24. The function computes the sum of the digits.
- A. This computes + first, as (s + x) mod 10. mod is evaluated before +.
- B. This stops before adding the leading digit 9, as with while (x ≧ 10).
- C. Correct. 9 + 0 + 8 + 7 = 24.
Continue: 9 more Programming Basics (Pseudocode Tracing) questions