AI InterviewSearch…Search problems, topics, or pages…Ctrl KGet started
Easyfor loopaccumulator

~60s

Repeated multiplication

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)
Show the answer and the worked solution

Correct answer: D.

81

Worked solution

  1. r starts at 1 and the loop runs 4 times with x = 3.
  2. The successive values of r are 3, 9, 27 and 81.
  3. 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.

Repeated multiplication — Pseudocode Aptitude Question

Repeated multiplication: What is printed? Answer and worked solution on CodeKairo.

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

  1. 12
  2. 27
  3. 64
  4. 81
Show the answer and the worked solution

Correct answer: D. 81

Worked solution

  1. r starts at 1 and the loop runs 4 times with x = 3.
  2. The successive values of r are 3, 9, 27 and 81.
  3. 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.

All Pseudocode questions · placement mock tests