AI InterviewSearch…Search problems, topics, or pages…Ctrl KGet started
Easywhile loopdigits

~60s

Adding the digits

/ is integer division and MOD is the remainder. What is printed?

Integer n, s
Set n = 9407
Set s = 0
While n > 0
    Set s = s + (n MOD 10)
    Set n = n / 10
End While
Print s
Show the answer and the worked solution

Correct answer: B.

20

Worked solution

  1. The digits pulled out, in order, are 7, 0, 4 and 9.
  2. s therefore becomes 7, then 7, then 11, then 20.
  3. n reaches 0 and the loop ends, printing 20.

Answer: 20.

The idea

Digit-sum loops always pair MOD 10 with / 10. The interior zero is worth noting because n is still positive after it, so the loop keeps going.

Shortcut. Casting out nines: 9407 leaves remainder 2 on division by 9, so its digit sum must too, and 20 is the only option that does.

Common trap. Stopping the trace when n reaches the single digit 9, as if the loop ran while n > 9, leaves s at 7 + 0 + 4 = 11; n = 9 still passes n > 0, so the leading 9 is added as well.

Adding the digits — Pseudocode Aptitude Question

Adding the digits: / is integer division and MOD is the remainder. What is printed? Answer and worked solution on CodeKairo.

Question

/ is integer division and MOD is the remainder. What is printed?

Integer n, s
Set n = 9407
Set s = 0
While n > 0
    Set s = s + (n MOD 10)
    Set n = n / 10
End While
Print s

Options

  1. 18
  2. 20
  3. 22
  4. 27
Show the answer and the worked solution

Correct answer: B. 20

Worked solution

  1. The digits pulled out, in order, are 7, 0, 4 and 9.
  2. s therefore becomes 7, then 7, then 11, then 20.
  3. n reaches 0 and the loop ends, printing 20.

Answer: 20.

The idea

Digit-sum loops always pair MOD 10 with / 10. The interior zero is worth noting because n is still positive after it, so the loop keeps going.

Shortcut. Casting out nines: 9407 leaves remainder 2 on division by 9, so its digit sum must too, and 20 is the only option that does.

Common trap. Stopping the trace when n reaches the single digit 9, as if the loop ran while n > 9, leaves s at 7 + 0 + 4 = 11; n = 9 still passes n > 0, so the leading 9 is added as well.

All Pseudocode questions · placement mock tests