index | submit | rank | book

digit-sum – Sum of decimal digits

Write a program that reads several integers and prints the sum of their decimal digits.

The sum of decimal digits of 720 is 7 plus 2 plus 0, i.e. 9.

Input and Output

Input will consist of several lines each with a number x where 0 ≤ x ≤ 1 000 000 000.

For each line of input, output should contain a line with a number s indicating the sum of the digits in x.

Input is terminated by the end-of-file (EOF).

Example input


Example output


The “digit sum” function

Your program should be implemented using a “digit sum” function that receives one integer and returns an integer indicating the sum of its digits. Please refer to the information for the chosen language:


Submit your solution to be graded according to the following list:


Here are some hints:

  1. Automated judge: Keep in mind that when your program is submitted it will not be run by a human but instead by an automated judge. Instructions should be followed exactly or the judge will not give you a full score. (And sometimes no score at all!)

  2. Produce output as you go: You do not need to accumulate input and then produce everything at the end. It is enough to produce output as you go. As soon as you read a number, write the corresponding result to the screen.

  3. Detecting the end of file. In this exercise, input is terminated by the end-of-file (EOF). The EOF can be simulated by the “ctrl-D” keystroke on the terminal/console session. Please see “processing input line by line” for details on how to do this.

  4. Processing digits. You can isolate the last digit of an integer by computing the remainder of the division by 10 (a.k.a. modulo). Likewise, you can remove the last digit by performing integer division of a number by 10.

  5. Integer division. Try to use a direct operator for integer division when it is available. However, if your programming language does not provide an integer division operator you can take the floor of the result of fractional division.

try first: repeat triple inc replace

try next: digit-count

index | submit | rank | book

Copyright © 2020-2023 Rudy Matela
All rights reserved