Skip to main content

Sum of digits until single digit

Short answer

Repeatedly replace the number by the sum of its digits (using n % 10 and n /= 10) until it becomes a single digit. For 12345, the intermediate sum is 15, then the final single digit is 6.

Write a program in C that calculates the sum of digits entered by the user successively until the sum reduces to a single digit number. For example, 12345 => 1+2+3+4+5=15=>1+5=6. (Find out sum of digit of number until the number becomes one digit number [891>18>9].)

Logic: repeatedly extract each digit with n % 10, add it, and remove it with n / 10. Take the sum as the new number and repeat until the number is below 10 (a single digit).

#include <stdio.h>
int main(void)
{
    long n;
    int sum;
    printf("Enter a number: ");
    scanf("%ld", &n);
    while (n > 9)
    {
        sum = 0;
        while (n > 0)
        {
            sum += n % 10;
            n /= 10;
        }
        printf("Sum of digits = %d\n", sum);
        n = sum;
    }
    printf("Single digit = %ld\n", n);
    return 0;
}

Output for 12345:

Enter a number: Sum of digits = 15
Sum of digits = 6
Single digit = 6

Output for 891:

Enter a number: Sum of digits = 18
Sum of digits = 9
Single digit = 9

Explanation

  • The inner while (n > 0) loop adds the digits: 1+2+3+4+5 = 15.
  • The outer loop while (n > 9) repeats with n = 15: 1+5 = 6, and 6 is a single digit, so it stops.

✓ Answer checked by Claude Opus 5.5 (high effort)

All Computer Programming chapter 5 questions →