ProgrammingVery hardProduct company OA

What is printed?

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

Correct answer: C. 5 2 -1

f(5) prints 5, then calls g(4), which calls f(2) (since 4-2=2); f(2) prints 2, then calls g(1), which calls f(-1) (since 1-2=-1); f(-1) hits n<=0 and returns -1 directly. That -1 is passed back up unchanged through g(1), f(2), g(4) and finally f(5), since each intermediate call simply returns what it received. Printed digits: 5 then 2; final value -1.

More C Programming questions

Exams that ask this topic