How many calls are made — Pseudocode Aptitude Question
How many calls are made: Counting the first call from the main program, how many times is G invoked in total? Answer and worked solution on CodeKairo.
- Topic: Pseudocode
- Section: Programming MCQs
- Difficulty: Medium
- Time target: 75 seconds
Question
Counting the first call from the main program, how many times is G invoked in total?
Function G(Integer n)
If n == 0 Then
Return 0
End If
Return n + G(n - 1)
End Function
Print G(5)Options
- 5
- 6
- 15
- 16
Show the answer and the worked solution
Correct answer: B. 6
Worked solution
- The chain of invocations is G(5), G(4), G(3), G(2), G(1) and finally G(0).
- G(0) returns without recursing further, so the chain stops there.
- Counting every entry in that list gives 6 invocations.
Answer: 6.
The idea
For a recursion that decrements by one from n down to 0 the number of calls is n + 1, because the base case is a call too. The value returned here is 15, which is the standing trap.
Shortcut. Count the arguments, not the arithmetic: each integer from 5 down to 0 is passed exactly once, so there are six calls.
Common trap. 5 forgets that G(0) is itself a call; it counts only the calls that recurse and stops before the base case.