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 toBin return when called as toBin(12)?
○integer: toBin(integer: x)
integer: y ← 0, p ← 1
while (x > 0)
y ← y + (x mod 2) × p
p ← p × 10
x ← x ÷ 2
endwhile
return y
- A11
- B100
- C1100
Show answer and explanation
Answer: C. 1100
x mod 2 is the ones digit in binary, and x ← x ÷ 2 shifts the binary number one digit to the right. x changes to 12, 6, 3, 1 and 0, producing the digits 0, 0, 1, 1 from the lowest. p grows tenfold each time, 1, 10, 100, 1000, so y = 0 × 1 + 0 × 10 + 1 × 100 + 1 × 1000 = 1100. The result writes the binary digits of 12 as the decimal digits of an integer.
- A. This stacks each digit on top, as in y ← y × 10 + x mod 2, which reverses the digit order (0011).
- B. This stops before adding the leading 1, as with while (x > 1).
- C. Correct. 12 is 1100 in binary.
Continue: 9 more Programming Basics (Pseudocode Tracing) questions