What will be the output of the following C program? void count (int n) {…

2016

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);
}

  1. A.

    3 1 2 2 1 3 4 4 4

  2. B.

    3 1 2 1 1 1 2 2 2

  3. C.

    3 1 2 2 1 3 4

  4. D.

    3 1 2 1 1 1 2

Attempted by 163 students.

Show answer & explanation

Correct answer: A

Answer: 3 1 2 2 1 3 4 4 4

Key idea: The variable d is declared static, so it is initialized once and shared across all recursive calls of count.

  • First call count(3): prints n = 3, prints d = 1, then increments d to 2 and calls count(2).

  • In count(2): prints n = 2, prints d = 2, then increments d to 3 and calls count(1).

  • In count(1): prints n = 1, prints d = 3, then increments d to 4. There is no further recursion.

  • After returning from count(1), the call count(2) resumes and prints the current d = 4.

  • After returning from count(2), the original call count(3) resumes and prints the current d = 4.

Putting all printed values in sequence: 3 1 2 2 1 3 4 4 4

A video solution is available for this question — log in and enroll to watch it.

Explore the full course: Gate Guidance By Sanchit Sir