The Sum of the Integer’s Digit – Solution

The challenge for this month’s Exercise is to tally the digits in an integer, reporting the sum. You must use math and not cheat by looking at the old solution, which I didn’t. Promise.

Though I’ve done this type of problem before, I devised what I believe to be a more clever solution than the first time.

Central to the solution is to use the modulus operator to lop off digits from a number:

a % 10

The result of this operation is the last digit in a decimal integer. When a has the value 1235, the result is 5. When a is 4002, the result is 2.

To obtain values for the rest of the digits, they must be shifted right one position. At the binary level, the C operator >> handles the task. For a decimal integer, however, you divide by ten:

a = a / 10;

When a is assigned the value 12345, the result of 12345/10 is 1234. Because a is an int variable, the .5 portion of the value is discarded.

Both of these expressions are put into a for loop, which tallies the digits in variable a, saving them in variable t:

for( t=0; a; a/=10 )
    t+= a % 10;

The for loop initializes variable t (the total) to zero. Variable a is passed to the sum() function, so it needs no initialization. But the value of variable a is used to terminate the loop. For each iteration, the value of variable a is divided by ten. The for loop’s statement uses the modulus operator to fetch the final digit in the number, adding it to the value of variable t.

Here is my full solution:

2023_07-Exercise.c

#include <stdio.h>

int sum(int a)
{
    int t;

    for( t=0; a; a/=10 )
        t+= a % 10;

    return(t);
}

int main()
{
    int d,t;

    /* beg for input */
    printf("Enter a positive integer: ");
    scanf("%d",&d);

    /* sum the digits */
    t = sum(d);
    printf("The sum of the digits is %d\n",t);

    return(0);
}

If you cheat and look at the original Exercise’s solution, you see this function:

int digit_sum(unsigned n)
{
    int total = 0;

    while(n)
    {
        total += n % 10;
        n /= 10;
    }

    /* if the value is over two-digits wide, recurse */
    if(total > 9)
        return(digit_sum(total));

    return(total);
}

The while loop approach is different and requires more overhead. I think my for loop solution is better, though both arrive at the same result. (Though remember that the original Exercise required further reduction of the digits, seen by the if(total > 9) statement near the end of the function.)

I hope your solution met with success. Remember, multiple ways exist to solve any programming puzzle.

Leave a Reply