ProgrammingHardHCL · Tech Mahindra pattern

What is printed?

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

Correct answer: A. 1 2 3 4 = 10

The recursive call f(n-1) happens BEFORE the printf, so the prints happen during unwinding in increasing order: the n=1 frame's printf runs first (after its own f(0) returns), then n=2, then n=3, then n=4: '1 2 3 4 '. The sum returned accumulates 1+2+3+4=10.

More C Programming questions

Exams that ask this topic