Tally the Digits, Again

Difficulty: ★ ★ ☆ ☆

Seven years ago (to this same date!) I wrote an Exercise to tally the digits in a number. The solution required that the sum be reduced to a single digit. For example, the sum of digits in 12345 is 15, which is then reduced to six.

Upon reflection, I wondered why I reduced the digits. After all, the sum of digits in the integer 12345 is 15. The result can be further reduced to six, but why? So I sought to re-write the solution using the string conversion method to tally the digits in an integer without reduction.

My original “Tally the Digits” Exercise featured two solutions. The first uses math, the second converts the number into a string. Without peeking at my original string solution, I sought to rewrite it for this week’s Lesson. Then I compared the two.

Here is my digit_sum() function from the Exercise’s string solution:

int digit_sum(unsigned n)
{
    char digits[32];
    char *d;
    int total;

    /* convert value to string */
    snprintf(digits,32,"%u",n);

    /* initialize variables */
    d = digits;
    total = 0;

    /* tally all the individual digits */
    while(*d)
    {
            /* subtract '0' from the character to
               retrieve its value */
        total += *d - '0';
        d++;
    }

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

    return(total);
}

For my update, I chose to use a for loop. This decision helped eliminate the initialization. Both variables used in the function, x and t, are initialized within the for loop statement.

Variable *d isn’t necessary because in the for loop I use an offset to peer into the converted string.

Finally, because I’m not reducing the value, the recursive call is removed from my sum() function. Here is my updated code with the new sum() function:

2023_07_01-Lesson.c

#include <stdio.h>

int sum(int a)
{
    char num[32];
    int x,t;

    snprintf(num,32,"%d",a);
    for( x=0, t=0; num[x]; x++ )
        t+=num[x]-'0';

    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);
}

The main() function could be reduced by eliminating variable t and outputting the result of sum(d) directly in the printf() statement. But I prefer a more readable presentation.

Here’s a sample run:

Enter a positive integer: 12345
The sum of the digits is 15

The second way of tallying the digits in an integer is to use math. This solution is presented in the original Exercise, but it’s also this month’s Exercise — again, without reducing the result.

Leave a Reply