ProgrammingHardAccenture · Cognizant pattern
What will be the output of the following pseudocode (tail-recursive factorial with an accumulator)?
What will be the output of the following pseudocode (tail-recursive factorial with an accumulator)?
Function factAcc(Integer n, Integer acc)
if (n <= 1)
return acc
end if
return factAcc(n - 1, acc * n)
End Function
Print factAcc(5, 1)- A. 120
- B. 24
- C. 60
- D. 720
Correct answer: A. 120
The accumulator carries the running product forward: acc becomes 1*5=5, then 5*4=20, then 20*3=60, then 60*2=120, and n=1 returns that final acc, 120.
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 (GCD of an entire list, folding pairwise)? Function gcdList(Array arr) Integer r =…
- What will be the output of the following pseudocode (counting permutations of a string via recursion)? Function countPerms(String s) if…
- What will be the output of the following pseudocode (basic run-length string compression, kept only if actually shorter)? Function…
- What will be the output of the following pseudocode (counting distinct substrings of length 2)? String s = "abab" Set subs = empty set for…
- What will be the output of the following pseudocode? (All variables are integers, so / is integer division.) Integer n = 20, steps = 0…
- What will be the output of the following pseudocode (counting all subsets of a set of size n)? Function countSubsets(Integer n) if (n ==…