What will be the output of the following pseudo code? For input a = 8 & b = 9.…

2025

What will be the output of the following pseudo code?

For input a = 8 & b = 9.

function (input a, input b)

If (a < b)

return function (b, a)

elseif (b != 0)

return (a + function (a, b - 1))

else

return 0

  1. A.

    56

  2. B.

    88

  3. C.

    72

  4. D.

    65

Attempted by 1 students.

Show answer & explanation

Correct answer: C

This is a recursive-function tracing question. To evaluate a recursive call for given inputs, apply the substitution method: expand each call using the function's own rules until the base case is reached, then combine the values returned from the base case back up through the calls.

Here the function first swaps its two arguments whenever the first is smaller than the second, so the larger value always ends up as 'a'. It then repeatedly adds 'a' to the result of the same function called with 'b' reduced by 1, continuing until 'b' becomes 0 (the base case, which returns 0). This is exactly the repeated-addition definition of multiplication: 'a' added to itself 'b' times equals a × b.

  1. function(8, 9): since 8 < 9, the condition holds, so it returns function(9, 8) — the arguments swap.

  2. function(9, 8): now 9 < 8 is false and b = 8 ≠ 0, so it returns 9 + function(9, 7).

  3. function(9, 7) returns 9 + function(9, 6).

  4. function(9, 6) returns 9 + function(9, 5).

  5. function(9, 5) returns 9 + function(9, 4).

  6. function(9, 4) returns 9 + function(9, 3).

  7. function(9, 3) returns 9 + function(9, 2).

  8. function(9, 2) returns 9 + function(9, 1).

  9. function(9, 1) returns 9 + function(9, 0).

  10. function(9, 0): here b = 0, so neither of the first two conditions holds, and it returns the else-branch value 0.

Collecting the additions from the calls with b = 8 down to b = 1, the value 9 is added once for each of those eight calls — that is 8 additions of 9. This matches the repeated-addition view from the concept above: 9 added to itself 8 times is 9 × 8.

So function(8, 9) evaluates to 72.

Explore the full course: Accenture Preparation