ProgrammingVery hardProduct company OA · GATE CS
What is printed?
What is printed?
long memo[50];
int calls = 0;
long f(int n) {
calls++;
if (n < 2) return n;
if (memo[n]) return memo[n];
return memo[n] = f(n - 1) + f(n - 2);
}
int main(void) {
long r = f(10);
printf("%ld %d", r, calls);
}- A. 55 19
- B. 55 177
- C. 55 11
- D. 89 19
Correct answer: A. 55 19
The first descent f(10) → f(9) → … → f(1) makes 10 calls. On the way back each f(n − 2) is either a cached hit or a base case: 9 more calls, 19 in all. Without the memo it would take 177 calls. f(10) = 55.
More C Programming questions
- With 4-byte int, what is printed? c int x = 7; printf("%zu %zu", sizeof (int) 3, sizeof x + 1);
- What is printed? c char s[8] = {'a', 'b'}; printf("%zu %zu %d", strlen(s), sizeof s, s[7]);
- What does r(3) print, and how many digits would r(6) print? c void r(int n) { if (n == 0) return; r(n - 1); printf("%d", n); r(n - 1); }
- What is printed? c const char s = "abcdefgh"; const char p = s + 2, q = strchr(s, 'g'); printf("%td %c %s", q - p, (p + (q - p) / 2), q);
- Given int f(int); and int (fp)(int) = f; which of these calls are valid? (i) fp(2) (ii) (fp)(2) (iii) (fp)(2) (iv) (&fp)(2)
- What is printed? c union U { int i; float f; } u = {3.9}; printf("%d", u.i);