GATE | GATE-CS-2016 (Set 1) | Question 45

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

Answer: (A)

Explanation:

count(3) will print value of n and d. So 3 1 will be printed 
and d will become 2. 

Then count(2) will be called. It will print value of n and d. 
So 2 2 will be printed and d will become 3. 

Then count(1) will be called. It will print value of n and d.
So 1 3 will be printed and d will become 4. 

Now count(1) will print value of d which is 4. count(1) will 
finish its execution. 

Then count(2) will print value of d which is 4. 

Similarly, count(3) will print value of d which is 4. 
So series will be A.

Leave a Reply

Your email address will not be published. Required fields are marked *