Tally the Digits

The programming adventure is full of interesting twists and turns, and with each new puzzle comes multiple opportunities to flex your coding skills and devise new solutions. For this month’s Exercise, the task is to take an integer value and add up all its digits. The mathematical term for this operation is a digit sum.

You’ve probably performed this type of exercise in the past. For example, suppose you have the number 135. When you add all the digits you get 9:

135 = 1 + 3 + 5 = 9

And if the sum is more than a single digit, you repeat the process:

246 = 2 + 4 + 6 = 12 = 1 + 2 = 3

The digit sum procedure is recursive, meaning that when the result is more than a single digit, you start over again until only a single digit remains.

I’m sure a mathematician can philosophize on the relevance of a digit sum, but that’s not the point of this month’s Exercise. You’re job is to come up with a function that returns the digit sum of an integer value. Here is a skeleton provided to help get you started:

#include <stdio.h>

int digit_sum(unsigned n)
{
}

int main()
{
    unsigned v;

    while(1)
    {
        printf("Type a positive number, 0 to quit: ");
        scanf("%u",&v);
        if( v == 0)
            break;
        printf("The sum of the digits is %d\n",
                digit_sum(v));
    }

    return(0);
}

Here is a sample run of how the program might work:

Type a positive number, 0 to quit: 123
The sum of the digits is 6
Type a positive number, 0 to quit: 246
The sum of the digits is 3
Type a positive number, 0 to quit: 20160701
The sum of the digits is 8
Type a positive number, 0 to quit: 0

I’ve provided the input loop for you. You need to code the digit_sum() function for the sample code. It receives an unsigned int value, n, which is magically manipulated to return a single digit value.

I know of at least two ways to accomplish this task. You can click here to view my solutions, but please try the Exercise on your own before peeking at what I did.

Leave a Reply