ProgrammingHardWipro · Cognizant pattern

What is printed?

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

Correct answer: A. t2 t1 t0 1

trace(n) always prints first and is false until n reaches 0, so f(2) recurses through f(1) into f(0) before trace returns true, printing t2 t1 t0 in order; the true result from f(0) then bubbles back up through the || chains, so f(2) returns 1.

More C Programming questions

Exams that ask this topic