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.
- Topic: Pseudocode
- Section: Programming MCQs
- Difficulty: Easy
- Time target: 60 seconds
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 sOptions
- 18
- 20
- 22
- 27
Show the answer and the worked solution
Correct answer: B. 20
Worked solution
- The digits pulled out, in order, are 7, 0, 4 and 9.
- s therefore becomes 7, then 7, then 11, then 20.
- 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.