The GATE Grind

GATE 2017 CS – Question 45

Programming and Data Structures · Recursion · 2 marks · Multiple choice

Consider the following two functions.

void fun1(int n) {
    if(n == 0) return;
    printf("%d", n);
    fun2(n - 2);
    printf("%d", n);
}

void fun2(int n) {
    if(n == 0) return;
    printf("%d", n);
    fun1(++n);
    printf("%d", n);
}

The output printed when `fun1(5)` is called is

  1. 53423122233445
  2. 53423120112233
  3. 53423122132435
  4. 53423120213243

Practise this question in The GATE Grind →

Show answer and explanation

Correct answer: (A) 53423122233445

Explanation

Trace the calls: `fun1(5)` prints 5, `fun2(3)` prints 3, `fun1(4)` prints 4, `fun2(2)` prints 2, `fun1(3)` prints 3, `fun2(1)` prints 1, and `fun1(2)` prints 2. Then `fun2(0)` returns at once. The calls now finish in reverse order, printing 2 (from `fun1(2)`), 2 (`fun2(1)`, where `n` is now 2), 3 (`fun1(3)`), 3 (`fun2(2)`), 4 (`fun1(4)`), 4 (`fun2(3)`) and 5 (`fun1(5)`). The output is 53423122233445.