ProgrammingModerateAccenture · Cognizant pattern
How many times is fib called in total (including the first call) when evaluating fib(5)?
How many times is fib called in total (including the first call) when evaluating fib(5)?
int fib(int n) {
if (n <= 1) return n;
return fib(n - 1) + fib(n - 2);
}- A. 25
- B. 5
- C. 15
- D. 9
Correct answer: C. 15
Calls C(n) = 1 + C(n-1) + C(n-2) with C(0) = C(1) = 1: C(2) = 3, C(3) = 5, C(4) = 9, C(5) = 15. 5 is the value fib(5) returns, not the number of calls.
More C Programming questions
- What is printed? c int x = 181, c = 0; while (x) { x &= x - 1; c++; } printf("%d", c);
- What is printed? c printf("%d", 1 << 3 + 1);
- On a typical compiler where int is 4 bytes and 4-byte aligned, what is printed? c struct S { char c; int i; char d; }; struct T { int i…
- With 4-byte int, consider int (p)[5]; Which is correct?
- int a[3][4]; is stored in row-major order starting at address 1000, with 4-byte int. What is the address of a[2][1]?
- What is printed? c unsigned char c = 250; c += 10; printf("%d", c);