ProgrammingHardInfosys · Capgemini pattern
What will be the output of the following pseudocode?
What will be the output of the following pseudocode?
Integer calls = 0
Integer Function f(Integer n)
calls = calls + 1
if (n <= 2) return 1
return f(n - 1) + f(n - 3)
End Function
Print f(7), calls- A. 9 9
- B. 9 17
- C. 13 17
- D. 9 15
Correct answer: B. 9 17
f(3..7) = 2, 3, 4, 6, 9. Calls satisfy C(n) = 1 + C(n − 1) + C(n − 3) with C(n) = 1 for n ≤ 2: C(3) = 3, C(4) = 5, C(5) = 7, C(6) = 11, C(7) = 17. The number of calls grows faster than the value's own recursion suggests.
Practise more Pseudocode and Code Tracing questionsPseudocode and Code Tracing: notes and key points
More Pseudocode and Code Tracing questions
- What will be the output of the following pseudocode? Integer a = 5, b, c, d b = a++ // post-increment c = ++a // pre-increment d = a + b +…
- What will be the output of the following pseudocode? Integer a[5] = {2, 4, 6, 8, 10} for (i = 1 to 4) a[i] = a[i] + a[i - 1] end for Print a
- What will be the output of the following pseudocode? Integer x = 1 for (i = 1 to 4) if (i mod 2 == 1) x = x i else x = x + i end if end…
- What will be the output of the following pseudocode? Integer n = 10, s = 0 for (i = 1 to n) if (n mod i == 0) s = s + i end if end for…
- What will be the output of the following pseudocode? Integer Function f(Integer x, Integer y) if (x > y) return f(x - y, y) if (x < y)…
- What will be the output of the following pseudocode? Integer s = 0, i = 0 while (true) i = i + 1 if (i mod 4 == 0) continue s = s + i if…