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
  1. A4
  2. B15
  3. 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.
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. ÷ 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)?
  2. 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?
  3. 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?
  4. ÷ 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?
  5. What does the following function s return when called as s(7)?