AI InterviewSearch…Search problems, topics, or pages…Ctrl KGet started
Mediumrecursioncounting

~75s

How many calls are made

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)
Show the answer and the worked solution

Correct answer: B.

6

Worked solution

  1. The chain of invocations is G(5), G(4), G(3), G(2), G(1) and finally G(0).
  2. G(0) returns without recursing further, so the chain stops there.
  3. 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.

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.

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

  1. 5
  2. 6
  3. 15
  4. 16
Show the answer and the worked solution

Correct answer: B. 6

Worked solution

  1. The chain of invocations is G(5), G(4), G(3), G(2), G(1) and finally G(0).
  2. G(0) returns without recursing further, so the chain stops there.
  3. 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.

All Pseudocode questions · placement mock tests