ProgrammingHardAccenture · Cognizant pattern

What is printed?

What is printed?
int depth = 0;
void f(int n) {
    depth++;
    if (n == 0) return;
    f(n - 1);
}
int main() {
    f(3);
    printf("%d", depth);
}
  1. A. 4
  2. B. 3
  3. C. 1
  4. D. 0

Correct answer: A. 4

depth is a global, incremented once at the START of every call, before checking the base case. f(3) calls f(2),f(1),f(0) — that's 4 total invocations (n=3,2,1,0), each incrementing depth once: final depth is 4.

More C Programming questions

Exams that ask this topic