Question

What will be the output of the following C program?

#include <stdio.h>
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);
}
Choose one option
Official answer and solution
Official answer
A
From
Official GATE 2016 answer key

Solution

Trace recursive activation frames and track the persistent state of the static variable.

In C, a static local variable inside a function is initialized only once and retains its value across all subsequent invocations.

Trace execution starting from count(3) with d = 1 initially:

  1. Call count(3):
    • Prints n (3): output 3
    • Prints d (1): output 1
    • d++   ⟹  d\implies d becomes 2
    • Since n>1n > 1 (3>13 > 1), calls count(2)
  1. Call count(2):
    • Prints n (2): output 2
    • Prints d (2): output 2
    • d++   ⟹  d\implies d becomes 3
    • Since n>1n > 1 (2>12 > 1), calls count(1)
  1. Call count(1):
    • Prints n (1): output 1
    • Prints d (3): output 3
    • d++   ⟹  d\implies d becomes 4
    • Since n>1n > 1 (1>11 > 1) is false, does not recurse
    • Prints d (4): output 4
  1. Unwinding recursive calls:
    • Control returns to count(2): prints d (4): output 4
    • Control returns to count(3): prints d (4): output 4

Concatenating all printed values gives: 3 1 2 2 1 3 4 4 4.

Final answer

A

Common trap

Assuming d is re-initialized to 1 on each recursive call, or forgetting the post-recursive print statement.

The answer is the one in the official GATE answer key. The solution is this site's own explanation.

Source

Paper
GATE 2016 Computer Science and Information Technology (CS) Session 1
Question
45 of 65, printed as CS Q.35
Section
Computer Science and Information Technology

Report an error in this question

GATE questions are the work of the organising institutes. This site is independent and is not affiliated with them.