ProgrammingVery hardProduct company OA · code-tracing level

What will be the output of the following pseudocode?

What will be the output of the following pseudocode?
Integer s = 0
Procedure p(Integer n)
    if (n == 0)
        return
    end if
    p(n - 1)
    s = s + n
    p(n - 1)
End Procedure

p(5)
Print s
  1. A. 31
  2. B. 57
  3. C. 15
  4. D. 80

Correct answer: B. 57

p(n) adds n once and calls p(n − 1) twice, so the value k is added 2^(5 − k) times: 5 once, 4 twice, 3 four times, 2 eight times, 1 sixteen times. s = 5 + 8 + 12 + 16 + 16 = 57. 31 = 2⁵ − 1 is the number of additions, not their sum; 15 = 1 + … + 5 treats each value as added once.

More Pseudocode and Code Tracing questions

Exams that ask this topic