ProgrammingHardWipro · Capgemini pattern

What will be the output of the following pseudocode? (/ is integer division; calls counts every call of f.)

What will be the output of the following pseudocode? (/ is integer division; calls counts every call of f.)
Integer calls = 0
Function digsum(Integer n)
    Integer s = 0
    while (n > 0)
        s = s + n mod 10
        n = n / 10
    end while
    return s
End Function
Function f(Integer n)
    calls = calls + 1
    if (n < 10)
        return n
    end if
    return f(digsum(n))
End Function
Print f(98765), calls
  1. A. 8 3
  2. B. 35 1
  3. C. 8 2
  4. D. 17 3

Correct answer: A. 8 3

98765 → digit sum 35 → digit sum 8 (single digit, so it is returned). f is called with 98765, 35 and 8: 3 calls. The result is the digital root, which also equals 98765 mod 9 = 8. '8 2' forgets the final call that returns 8.

More Pseudocode and Code Tracing questions

Exams that ask this topic