ProgrammingHardIBM · Deloitte pattern

What is printed?

What is printed?
#include <stdio.h>
void count(int n) {
    int local = n;
    if (n == 0) { printf("local=%d ", local); return; }
    count(n - 1);
    printf("local=%d ", local);
}
int main(void) {
    count(3);
}
  1. A. local=0 local=1 local=2 local=3
  2. B. local=3 local=3 local=3 local=3
  3. C. local=0 local=0 local=0 local=0
  4. D. local=3 local=2 local=1 local=0

Correct answer: A. local=0 local=1 local=2 local=3

Each recursive call gets its own independent stack frame, so each call's local keeps the value it was given even while deeper calls run. Printing happens only on the way back up, in the order the calls return: n=0 first, then 1, 2, 3.

More C Programming questions

Exams that ask this topic