ProgrammingVery hardTCS NQT Advanced · Capgemini
What will be the output of the following pseudocode? (the static s keeps its value between calls; in f(n - 1) + s the call is evaluated first)
What will be the output of the following pseudocode? (the static s keeps its value between calls; in f(n - 1) + s the call is evaluated first)
Function f(Integer n)
static Integer s = 0
s = s + n
if (n <= 1)
return s
end if
return f(n - 1) + s
End Function
Print f(4)- A. 30
- B. 40
- C. 20
- D. 10
Correct answer: B. 40
s is shared by all calls and is read only after f(n − 1) returns, by which time it has become 4 + 3 + 2 + 1 = 10. So f(1) = 10, f(2) = 20, f(3) = 30, f(4) = 40. Reading s before the call gives the trap 30.
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 c = 0 for (each i from 1 to 6) for (each j from 1 to 6) if ((i j) mod 4 == 0)…
- What will be the output of the following pseudocode? (Strings are indexed from 0; + joins strings) String s = "AAABCCDAA", r = "" Integer…
- What will be the output of the following pseudocode? (All variables are integers, so / is integer division) Function f(Integer n) if (n ==…
- What will be the output of the following pseudocode? (ref means the argument is passed by reference; other parameters are copies)…
- What will be the output of the following pseudocode? (/ is integer division) Stack st = empty for each token t in "6 2 3 + - 3 8 2 / + "…
- What will be the output of the following pseudocode? Integer a = 144, b = 89, t, steps = 0 while (b != 0) t = a mod b a = b b = t steps =…