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

~150s

Two routines calling each other

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

Correct answer: B.

10

Worked solution

  1. A(4) = 4 + B(3), and B(3) = 3 * A(2).
  2. A(2) = 2 + B(1), and B(1) = 1 A(0) = 1 0 = 0.
  3. So A(2) = 2 + 0 = 2, and B(3) = 3 * 2 = 6.
  4. 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.

Two routines calling each other — Aptitude Question

Two routines calling each other: What is printed? Answer and worked solution on CodeKairo.

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

  1. 6
  2. 10
  3. 14
  4. 24
Show the answer and the worked solution

Correct answer: B. 10

Worked solution

  1. A(4) = 4 + B(3), and B(3) = 3 * A(2).
  2. A(2) = 2 + B(1), and B(1) = 1 A(0) = 1 0 = 0.
  3. So A(2) = 2 + 0 = 2, and B(3) = 3 * 2 = 6.
  4. 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.

All Pseudocode questions · placement mock tests