ProgrammingVery hardProduct company OA · code-tracing level
What will be the output of the following pseudocode? (calls counts every call, including the first.)
What will be the output of the following pseudocode? (calls counts every call, including the first.)
Integer calls = 0
Function g(Integer n)
calls = calls + 1
if (n < 3)
return 1
end if
return g(n - 1) + g(n - 3)
End Function
Print g(10), calls- A. 28 28
- B. 28 55
- C. 19 55
- D. 28 37
Correct answer: B. 28 55
Values: g(0) = g(1) = g(2) = 1, then g(n) = g(n − 1) + g(n − 3): 2, 3, 4, 6, 9, 13, 19, 28, so g(10) = 28. Calls obey C(n) = 1 + C(n − 1) + C(n − 3) with C(0) = C(1) = C(2) = 1: C(3) = 3, 5, 7, 11, 17, 25, 37, C(10) = 55. 28 confuses the value with the number of calls (they agree only at the leaves); 37 is C(9).
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? (& is bitwise AND and >> is a right shift.) Integer c = 0 for (each x from 1 to 200)…
- What will be the output of the following pseudocode? (Integers are in two's complement, so −i flips the bits of i and adds 1; & is bitwise…
- What will be the output of the following pseudocode? (& is bitwise AND.) Integer c = 0, x for (each i from 0 to 63) x = i while (x > 0) x…
- What will be the output of the following pseudocode? Integer n = 30, c = 0, j for (each i from 1 to n) j = i while (j <= n) c = c + 1 j =…
- What will be the output of the following pseudocode? Integer c = 0 for (i = 1; i <= 100; i = i 2) for (j = i; j <= 100; j = j + 1) c = c +…
- What will be the output of the following pseudocode? // 32-bit signed integers; overflow wraps around (two's complement); / truncates…