Two routines calling each other — Aptitude Question
Two routines calling each other: What is printed? Answer and worked solution on CodeKairo.
- Topic: Pseudocode
- Section: Programming MCQs
- Difficulty: Hard
- Time target: 150 seconds
Question
What is printed?
Function A(Integer n)
If n <= 0 Then
Return 0
End If
Return n + B(n - 1)
End Function
Function B(Integer n)
If n <= 0 Then
Return 0
End If
Return n * A(n - 1)
End Function
Print A(4)Options
- 6
- 10
- 14
- 24
Show the answer and the worked solution
Correct answer: B. 10
Worked solution
- A(4) = 4 + B(3), and B(3) = 3 * A(2).
- A(2) = 2 + B(1), and B(1) = 1 A(0) = 1 0 = 0.
- So A(2) = 2 + 0 = 2, and B(3) = 3 * 2 = 6.
- Finally A(4) = 4 + 6 = 10.
Answer: 10.
The idea
Mutual recursion is traced exactly like ordinary recursion: descend to the base case writing each pending expression, then substitute upwards. The multiplication in B collapses whole branches, so the total is far below the factorial-style 24.
Shortcut. B(1) = 1 × A(0) = 0 wipes out everything below it, so A(4) = 4 + 3 × (2 + 0) = 10.
Common trap. 6 is B(3) on its own; it forgets the pending 4 + that A(4) still has to add once B(3) returns.