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
  1. A11
  2. B100
  3. 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.
Practice this topic Back to topic

Related calculators

Books on Programming Basics (Pseudocode Tracing) Ad

As an Amazon Associate I earn from qualifying purchases.

More Programming Basics (Pseudocode Tracing) questions

  1. The following program subtracts the two integers a and b from each other until they are equal. What is the value of k after it runs?
  2. The following function isLeap returns true if the year y is a leap year. and is evaluated before or. For which y does isLeap(y) return true?
  3. ÷ is division; when the result is assigned to an integer variable (including a function argument), the fractional part is discarded. When the following function pow is called as pow(2, 10), how many times is pow called, including the first call?
  4. What does the following function s return when called as s(7)?
  5. When the following procedure p is called as p(3), what sequence of values is output?