{
static int d = 1;
printf("%d ", n);
printf("%d ", d);
d++;
if(n > 1) count(n-1);
printf("%d ", d);
}
int main()
{
count(3);
}
Correct : C
Given:
A recursive function count(int n) with a static variable static int d = 1, called initially as count(3).
To find:
Output of the program.
Solution:
The variable d is static, so it persists across all recursive calls and gets initialized only once.
Let me trace the calls step by step on a recursion stack.
First, main() calls count(3):
Here n = 3, and d starts at 1.
It prints n and then d:
Output so far: 3 1
Now d increments, so d = 2.
Since n > 1 (3 > 1 is true), it calls count(2).
Inside count(2):
Here n = 2, and current d = 2.
It prints n and d:
Output so far: 3 1 2 2
Now d increments, so d = 3.
Since n > 1 (2 > 1 is true), it calls count(1).
Inside count(1):
Here n = 1, and current d = 3.
It prints n and d:
Output so far: 3 1 2 2 1 3
Now d increments, so d = 4.
Since n > 1 (1 > 1 is false), the if condition fails, so no further call is made.
Now it executes the next statement and prints d:
Output so far: 3 1 2 2 1 3 4
Now count(1) finishes and returns to count(2).
Back in count(2):
It prints d, which is currently 4:
Output so far: 3 1 2 2 1 3 4 4
Now count(2) finishes and returns to count(3).
Back in count(3):
It prints d, which is still 4:
Output so far: 3 1 2 2 1 3 4 4 4
Now count(3) finishes and the program ends.
So the complete printed sequence is: 3 1 2 2 1 3 4 4 4.
Answer:
(A) 3 1 2 2 1 3 4 4 4
Similar Questions
Total Unique Visitors