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
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):
fun1(5): prints5, callsfun2(3).fun2(3): prints3, increments to 4 (++n), callsfun1(4).fun1(4): prints4, callsfun2(2).fun2(2): prints2, increments to 3 (++n), callsfun1(3).fun1(3): prints3, callsfun2(1).fun2(1): prints1, increments to 2 (++n), callsfun1(2).fun1(2): prints2, callsfun2(0).fun2(0): , returns immediately without printing.
Now trace the returns from the call stack:
fun1(2)resumes: prints its local , returns.fun2(1)resumes: its local was incremented to 2, so prints2, returns.fun1(3)resumes: prints its local , returns.fun2(2)resumes: its local was incremented to 3, so prints3, returns.fun1(4)resumes: prints its local , returns.fun2(3)resumes: its local was incremented to 4, so prints4, returns.fun1(5)resumes: prints its local , 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).
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.