The Sum of the Integer’s Digit Is . . .

Difficulty: ★ ★ ☆ ☆

Yes, this Exercise has been done before. But back then, exactly seven years ago, I had the digits reduced further so that the result was a single digit. This time, your goal is to tally the digits in an integer and report the results — no reductions!

To tally digits in an integer you take a value such as 1155448. This integer contains digits that total to 28. Your solution to this Exercise consumes a value such as 1155448 and outputs the sum of those individual digits, which is equal to 28.

The Exercise from seven years ago had you reduce the value further. So 28 becomes ten, which becomes one. That’s not the task at hand for this challenge. No, your job is not to reduce the tally.

Today’s Lesson covers the string method of reducing digits. This approach is valid, but it’s not what I’m requesting for a solution. Instead, you must use frightening math to reduce the digits. Here’s a sample run:

Enter a positive integer: 1155448
The sum of the digits is 28

Do not cheat by looking up the old solution!

Feel free to borrow the main() function from today’s Lesson. Your task is to rewrite the sum() function so that it uses a for loop and math operations to reduce the digits. (The original solution, which you’re not to peek at, uses a while loop.)

Please try this Exercise on your own before you check out my solution, or you can cheat and look at the original Exercise’s solution. Click here to view my solution.

Leave a Reply