Computer Sciences > Gate 2016 Set-1 > C code
What will be the output of the following C program?

void count(int n)
{
    static int d = 1;
    printf("%d ", n);
    printf("%d ", d);
    d++;
    if(n > 1) count(n-1);
    printf("%d ", d);
}
int main()
{
    count(3);
}


A
3 1 2 2 1 3 4 4 4
B
3 1 2 1 1 1 2 2 2
C
3 1 2 2 1 3 4
D
3 1 2 1 1 1 2

Correct : C

Given:
A recursive function count(int n) with a static variable d = 1, called initially as count(3).
To find:
The output printed on the console.
Solution:
Let me trace the function execution call by call.
Notice that d is static, so it is initialized to 1 only once and retains its updated value across all recursive calls.
First call: count(3)
Here, n = 3 and current d = 1.
Printing n gives: 3
Printing d gives: 1
Now incrementing d by 1, so d becomes 2.
Check condition: (n > 1) which is 3 > 1 (True).
So, it makes a recursive call: count(2).
Second call: count(2)
Here, n = 2 and current d = 2.
Printing n gives: 2
Printing d gives: 2
Now incrementing d by 1, so d becomes 3.
Check condition: (n > 1) which is 2 > 1 (True).
So, it makes a recursive call: count(1).
Third call: count(1)
Here, n = 1 and current d = 3.
Printing n gives: 1
Printing d gives: 3
Now incrementing d by 1, so d becomes 4.
Check condition: (n > 1) which is 1 > 1 (False).
Now printing the final line of count(1): printf("%d ", d), which prints: 4
The call count(1) finishes and returns back to count(2).
Back in count(2):
Now executing the line after the recursive call: printf("%d ", d).
Since d is currently 4, it prints: 4
The call count(2) finishes and returns back to count(3).
Back in count(3):
Now executing the line after the recursive call: printf("%d ", d).
Since d is still 4, it prints: 4
The call count(3) finishes and returns to main().
Putting all printed values together in order:
3 1 2 2 1 3 4 4 4
Answer:
(A) 3 1 2 2 1 3 4 4 4

Similar Questions

Consider the following program in C language: #include <stdio.h> main() {     int i;     int *pi = &i;     scanf("%d",...
#16 MCQ
Consider the following two C code segments. Y and X are one and two dimensional arrays of size n and n × n respectively, where 2 ≤ n ≤ 10. Assume that in both c...
#25 MCQ
Consider the following C program segment. #include<stdio.h> int main( ) {     char s1[7] = "1234", *p;     p = s1 + 2;    ...
#37 MCQ

Related Topics

C program output GATE computer science 2016 recursive function C count function in C printf statement usage static variable in C recursion depth C GATE 2016 Set-1 C programming questions

Unique Visitor Count

Total Unique Visitors

Loading......