ProgrammingVery hardProduct company OA · code-tracing level
What will be the output of the following pseudocode? (g is a global variable.)
What will be the output of the following pseudocode? (g is a global variable.)
Integer g = 0
Function f(Integer n)
if (n == 0)
return 0
end if
g = g + n
Integer r = f(n - 1)
return r + g
End Function
Print f(4), g- A. 30 10
- B. 20 10
- C. 40 4
- D. 40 10
Correct answer: D. 40 10
All the additions to g happen on the way down: g becomes 4, 7, 9, 10 before any call returns. Every level then reads g after its recursive call, when g is already 10. So f(1) = 0 + 10, f(2) = 10 + 10, f(3) = 30, f(4) = 40, and g = 10. 30 = 4 + 7 + 9 + 10 assumes each level adds the value g had when that level started.
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? (Integers are passed by value. An array parameter receives a reference to the…
- What will be the output of the following pseudocode? (&& binds more tightly than ||, and both stop evaluating as soon as the result is…
- What will be the output of the following pseudocode? Integer c = 0, i for (i = 1; i <= 50; i = i + 1) i = i 2 c = c + 1 end for Print c, i
- What will be the output of the following pseudocode? (Arrays are indexed from 0.) Integer a[8] = {1, 2, 3, 4, 6, 7, 8, 9} Integer i = 0, j…
- What will be the output of the following pseudocode? (Arrays are indexed from 0; a 'from a down to b' loop does nothing when a < b.)…
- What will be the output of the following pseudocode? // 32-bit signed integers; overflow wraps around (two's complement) Integer f = 1 for…