ProgrammingHardWipro · Cognizant pattern
What happens when this runs?
What happens when this runs?
int fibonacci(int n) {
if (n <= 1) return n;
return fibonacci(n - 1) + fibonacci(n - 2);
}
int main(void) {
printf("%d", fibonacci(-5));
}- A. It recurses forever (or until stack overflow), since n keeps decreasing without ever becoming positive
- B. Undefined behaviour: fibonacci is not designed for negative input
- C. It returns -5 immediately: -5 <= 1 is true, so the base case triggers right away with no further recursion at all
- D. Compile-time error: fibonacci cannot be called with a negative argument
Correct answer: C. It returns -5 immediately: -5 <= 1 is true, so the base case triggers right away with no further recursion at all
n <= 1 is checked FIRST, and -5 <= 1 is true, so the function returns n (-5) immediately without ever reaching the recursive case — there's no infinite recursion here, since the very first call already satisfies the base case. It just produces a nonsensical (but well-defined) negative Fibonacci value because the function was never designed to validate its input.
More C Programming questions
- Assume 32-bit int. What is printed? c int arr[3] = {1, 2, 3}; int total = 0; int i; for (i = 0; i < 3; i++) total = total + arr[i]…
- Assume a 64-bit LP64 ABI. What is printed? c int createZeroed(int n) { int arr = calloc(n, sizeof(int)); return arr; } int main(void) {…
- Assume 32-bit int. What is printed? c int x = 5; int y = x-- - --x; printf("%d %d", x, y);
- Assume a 64-bit LP64 ABI. What is printed? c struct Pair { int first; int second; }; struct Pair makePair(int a, int b) { return (struct…
- What is printed? c int main(void) { int a = 10, b = 3; printf("%d %d %f", a / b, a % b, (float)a / b); }
- What is printed? c int main(void) { char ch = 'A'; int code = ch + 1; printf("%d %c", code, (char)code); }