Skip to content
Official PYQ · 2017

GATE CS 2017 Set 1 Q35 — Recursion

Explain with AI

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)\text{fun1}(5) is called is

Choose one option
View worked solution

Answer: A

To find the output of fun1(5), we trace the execution step-by-step. Note the crucial detail in fun2(n): the call fun1(++n) uses the pre-increment operator. This increments the local variable n in fun2 before passing it to fun1, meaning the subsequent printf("%d", n) in fun2 will print this incremented value.

Let's trace the calls from the bottom up (starting from the base case):

  • fun2(0): Returns immediately (prints nothing).
  • fun1(2):
    • Prints 2
    • Calls fun2(0)
    • Prints 2
    • Output: 22
  • fun2(1):
    • Prints 1
    • Increments n to 2 and calls fun1(2) (which outputs 22)
    • Prints 2 (the incremented value of n)
    • Output: 12222 →\rightarrow 1222
  • fun1(3):
    • Prints 3
    • Calls fun2(1) (which outputs 1222)
    • Prints 3
    • Output: 312223
  • fun2(2):
    • Prints 2
    • Increments n to 3 and calls fun1(3) (which outputs 312223)
    • Prints 3
    • Output: 23122233
  • fun1(4):
    • Prints 4
    • Calls fun2(2) (which outputs 23122233)
    • Prints 4
    • Output: 4231222334
  • fun2(3):
    • Prints 3
    • Increments n to 4 and calls fun1(4) (which outputs 4231222334)
    • Prints 4
    • Output: 342312223344
  • fun1(5):
    • Prints 5
    • Calls fun2(3) (which outputs 342312223344)
    • Prints 5
    • Output: 53423122233445

Thus, the final printed output is 53423122233445.

Free practice · Your answers on this page are not saved.

Published
Report a correction
Keep exploringMore Recursion questions