Question
What will be the output of the following C program?
#include <stdio.h>
void count(int n) {
static int d = 1;
printf("%d ", n);
printf("%d ", d);
d++;
if (n > 1) count(n - 1);
printf("%d ", d);
}
void main() {
count(3);
}
Official answer and solution
- Official answer
- A
- From
- Official GATE 2016 answer key
Solution
Trace recursive activation frames and track the persistent state of the static variable.
In C, a static local variable inside a function is initialized only once and retains its value across all subsequent invocations.
Trace execution starting from count(3) with d = 1 initially:
- Call
count(3):- Prints
n(3): output3 - Prints
d(1): output1 d++becomes 2- Since (), calls
count(2)
- Prints
- Call
count(2):- Prints
n(2): output2 - Prints
d(2): output2 d++becomes 3- Since (), calls
count(1)
- Prints
- Call
count(1):- Prints
n(1): output1 - Prints
d(3): output3 d++becomes 4- Since () is false, does not recurse
- Prints
d(4): output4
- Prints
- Unwinding recursive calls:
- Control returns to
count(2): printsd(4): output4 - Control returns to
count(3): printsd(4): output4
- Control returns to
Concatenating all printed values gives: 3 1 2 2 1 3 4 4 4.
A
Assuming d is re-initialized to 1 on each recursive call, or forgetting the post-recursive print statement.
The answer is the one in the official GATE answer key. The solution is this site's own explanation.
Source
- Paper
- GATE 2016 Computer Science and Information Technology (CS) Session 1
- Question
- 45 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.