ProgrammingVery hardTCS NQT · Accenture

The procedure below counts the numbers from 1 to 1000 whose digit sum is exactly 5. It uses digit-sum by repeated division. What is printed?

The procedure below counts the numbers from 1 to 1000 whose digit sum is exactly 5. It uses digit-sum by repeated division. What is printed?
count = 0
for n = 1 to 1000
    s = 0; m = n
    while m > 0: s = s + m mod 10; m = m div 10
    if s == 5 then count = count + 1
end for
Print count
  1. A. 15
  2. B. 21
  3. C. 28
  4. D. 56

Correct answer: B. 21

Three-digit strings with leading zeros and digit sum 5 number C(7,2) = 21, and 1000 has digit sum 1, so the answer is 21. Testing digit sum 4 gives 15, digit sum 6 gives 28, and testing at most 5 gives 56.

More Pseudocode and Code Tracing questions

Exams that ask this topic