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 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

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 in C GATE 2016 Set-1 C programming questions

Unique Visitor Count

Total Unique Visitors

Loading......