ProgrammingHardTCS NQT · Infosys pattern

What is printed?

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

Correct answer: D. 5 0

Passing a pointer means every recursive call shares and mutates the SAME x (unlike passing n by value). Each call decrements x by 1 and adds 1 to the count, running 5 times until *n reaches 0, so f returns 5 and x ends at 0.

More C Programming questions

Exams that ask this topic