GateAI
Recursion

GATE CSE 2016 Set 1 · Q35

MCQ2 marksMedium

Time

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); } void main(){ count(3); }

Select one answerSingle correct

Pick an option to check

Solution

Step-by-step verified solution

Official answer: A) 3 1 2 2 1 3 4 4 4

Recursion

The variable d is declared as static int d = 1;, so it is initialized once and retains its value across recursive calls.

Let's trace the execution of count(3):

  1. count(3) called:

    • Prints n (which is 3) and d (which is 1). Output so far: 3 1

    • d is incremented to 2.

    • Since n>1n > 1 (3>13 > 1), it calls count(2).

  2. count(2) called:

    • Prints n (which is 2) and d (which is 2). Output so far: 3 1 2 2

    • d is incremented to 3.

    • Since n>1n > 1 (2>12 > 1), it calls count(1).

  3. count(1) called:

    • Prints n (which is 1) and d (which is 3). Output so far: 3 1 2 2 1 3

    • d is incremented to 4.

    • Since n>1n > 1 (1>11 > 1) is false, it does not make another recursive call.

    • Prints d (which is 4). Output so far: 3 1 2 2 1 3 4

    • count(1) returns to count(2).

  4. Returning through the recursion stack:

    • In count(2): prints d (which is 4). Output so far: 3 1 2 2 1 3 4 4

    • count(2) returns to count(3).

    • In count(3): prints d (which is 4). Output so far: 3 1 2 2 1 3 4 4 4

Thus, the complete output is 3 1 2 2 1 3 4 4 4, which matches option (A).

Try the question first, then check your work.

Think the official key or this write-up is wrong?

Report error or challenge

Examiner trap

The misconception this question tests

This Recursion previous year question is Q35 of the GATE CSE 2016 Set 1 paper. Find more GATE CSE PYQs on Recursion in Programming and Data Structures, or browse all GATE CSE PYQs.

Free diagnostic

Where do you stand for GATE?

Take the 20-minute diagnostic: the 3 topics that cost you the most marks, and a rank range. Or sit 5 related Recursion PYQs now with no account.

One GATE CSE PYQ every morning

An official question by email at 7 AM IST, with a link to its verified solution. Unsubscribe in one click.

Recursion in GATE CSE

Recursion has 19 GATE CSE PYQs across 15 papers from 2011 to 2026. 10 of them are 2-mark MCQs like this one, and it is the only one in GATE CSE 2016 Set 1.

How GATE tests Recursion

More from GATE CSE 2016 Set 1

Share this solution

A plain-text card for WhatsApp or Telegram study groups.

GateAI solution cardGATE CSE 2016 Set 1 · Q35 · MCQ

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); } void main(){ count(3); }

Topic-wise GATE CS PYQs with verified steps

Independent practice explanation verified by the GateAI team. GATE is conducted by the IITs; question text follows the official paper.