OverIQ.com

C Program to find the sum of the digits of a number untill the sum is reduced to a single digit

Last updated on July 27, 2020


The following is a C program to find the sum of the digits till the sum is reduced to a single digit.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
/**************************************************************************************************
 * Program to find the sum of the digits of a number till the sum is reduced to a single digit
***************************************************************************************************/

#include<stdio.h> // include stdio.h

int main()
{    
    long int num;
    int sum = 0, rem;

    printf("Enter a number: ");
    scanf("%ld", &num);   

    while(num / 10 != 0)
    {
        sum = 0;
        while(num != 0) 
        {
            rem = num % 10;  // get the last digit of num
            sum += rem;      // add rem to sum
            num = num / 10;  // remove the last digit from num
        }

        num = sum;
    }

    printf("%d", sum);

    return 0;
}

Expected Output: 1st run:

1
2
Enter a number: 12345
6

2nd run:

1
2
Enter a number: 749
2

How it works #

The following table demonstrates what happens a each iteration of the inner while loop, assuming num = 12345:

Iteration num sum rem
After 1st iteration remainder = 12345%10 = 5 sum = 0+5 = 5 num = 12345/10 = 1234
After 2nd iteration remainder = 1234%10 = 4 sum = 5+4 = 9 num = 1234/10 = 123
After 3rd iteration remainder = 123%10 = 3 sum = 9+3 = 12 num = 123/10 = 12
After 4th iteration remainder = 12%10 = 2 sum = 12+2 = 14 num = 12/10 = 1
After 5th iteration remainder = 1%10 = 1 sum = 14+1 = 15 num = 1/10 = 0

This completes the first iteration of the outer while loop. Since the num is still not reduced to single digit, the condition num / 10 != 0 evaluates to true (1) and the body of inner while loop is executed again.

Iteration num sum rem
After 1st iteration remainder = 15%10 = 5 sum = 0+5 = 5 num = 15/10 = 1
After 2nd iteration remainder = 1%10 = 1 sum = 5+1 = 6 num = 1/10 = 0

Recommended Reading: