Repeated multiplication — Pseudocode Aptitude Question
Repeated multiplication: What is printed? Answer and worked solution on CodeKairo.
- Topic: Pseudocode
- Section: Programming MCQs
- Difficulty: Easy
- Time target: 60 seconds
Question
What is printed?
Function P(Integer x, Integer n)
Integer r, i
Set r = 1
For i = 1 to n
Set r = r * x
End For
Return r
End Function
Print P(3, 4)Options
- 12
- 27
- 64
- 81
Show the answer and the worked solution
Correct answer: D. 81
Worked solution
- r starts at 1 and the loop runs 4 times with x = 3.
- The successive values of r are 3, 9, 27 and 81.
- The routine returns 81, which is 3 raised to the power 4.
Answer: 81.
The idea
An accumulator that starts at 1 and multiplies is a power routine; one that starts at 0 and adds is a multiplication routine. The distractor 27 is 3 cubed, from running the loop one time too few.
Shortcut. Powers of 3 end in 3, 9, 7, 1 in turn, so the fourth power ends in 1, and 81 is the only option that does.
Common trap. 64 is 4³, the result of swapping the arguments and reading P(3, 4) as base 4 with exponent 3.