Question

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

Choose one option
Official answer and solution
Official answer
A
From
Official GATE 2017 answer key

Solution

Trace the mutual recursive calls and print statements of fun1 and fun2 on the execution call stack.

We are given two mutually recursive 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);
}

Trace the execution starting from fun1(5):

  1. fun1(5): prints 5, calls fun2(3).
  2. fun2(3): prints 3, increments nn to 4 (++n), calls fun1(4).
  3. fun1(4): prints 4, calls fun2(2).
  4. fun2(2): prints 2, increments nn to 3 (++n), calls fun1(3).
  5. fun1(3): prints 3, calls fun2(1).
  6. fun2(1): prints 1, increments nn to 2 (++n), calls fun1(2).
  7. fun1(2): prints 2, calls fun2(0).
  8. fun2(0): n==0n == 0, returns immediately without printing.

Now trace the returns from the call stack:

  • fun1(2) resumes: prints its local n=2n = 2, returns.
  • fun2(1) resumes: its local nn was incremented to 2, so prints 2, returns.
  • fun1(3) resumes: prints its local n=3n = 3, returns.
  • fun2(2) resumes: its local nn was incremented to 3, so prints 3, returns.
  • fun1(4) resumes: prints its local n=4n = 4, returns.
  • fun2(3) resumes: its local nn was incremented to 4, so prints 4, returns.
  • fun1(5) resumes: prints its local n=5n = 5, returns.

Concatenating the printed digits in order gives:
5 3 4 2 3 1 2 2 2 3 3 4 4 5
which is 53423122233445 (Option A).

Final answer

A

The answer is the one in the official GATE answer key. The solution is this site's own explanation.

Source

Paper
GATE 2017 Computer Science and Information Technology (CS) Session 1
Question
35 of 65, printed as CS Q.35
Section
Computer Science and Information Technology

Report an error in this question

GATE questions are the work of the organising institutes. This site is independent and is not affiliated with them.