You are here

Sum of digits in C

C program to calculate the sum of digits of a number: we will use modulus operator (%) to extract individual digits of a number and keep on adding them.

C programming code

  1. #include <stdio.h>
  2.  
  3. int main()
  4. {
  5.    int n, t, sum = 0, remainder;
  6.  
  7.    printf("Enter an integer\n");
  8.    scanf("%d", &n);
  9.  
  10.    t = n;
  11.  
  12.    while (t != 0)
  13.    {
  14.       remainder = t % 10;
  15.       sum       = sum + remainder;
  16.       t         = t / 10;
  17.    }
  18.  
  19.    printf("Sum of digits of %d = %d\n", n, sum);
  20.  
  21.    return 0;
  22. }

If you wish you can modify the input variable (n) and without using an additional variable (t) but it isn't recommended.

Output of program:
Sum of digits C program output

For example, if the input is 98, the variable sum is 0 initially
98%10 = 8 (% is modulus operator which gives us remainder when 98 is divided by 10).
sum = sum + remainder
so sum = 8 now.
98/10 = 9 because in C language whenever we divide an integer by an another integer we get an integer.
9%10 = 9
sum = 8 (previous value) + 9
sum = 17
9/10 = 0.
So finally n = 0, the loop ends we get the required sum.

Download Add digits program.

Calculate sum of digits in C without modulus operator

C program to find the sum of digit(s) of an integer which does not use modulus operator. Our program uses a character array (string) for storing an integer. We convert every character of the string into an integer and add all these integers.

  1. #include <stdio.h>
  2.  
  3. int main()
  4. {
  5.    int c, sum, t;
  6.    char n[1000];
  7.    
  8.    printf("Input an integer\n");
  9.    scanf("%s", n);
  10.  
  11.    sum = c = 0;
  12.    
  13.    while (n[c] != '\0') {
  14.       t   = n[c] - '0'; // Converting character to integer
  15.       sum = sum + t;
  16.       c++;
  17.    }
  18.  
  19.    printf("Sum of digits of %s = %d\n", n, sum);
  20.  
  21.    return 0;
  22. }

An advantage of this method is that input integer can be very large which can't be stored in an int or a long long variable, see an example below.

Output of program:

  1. Input an integer
  2. 123456789123456789123456789
  3. Sum of digits of 123456789123456789123456789 = 135

Sum of digits of a number C program using recursion

  1. #include <stdio.h>
  2.  
  3. int add_digits(int);
  4.  
  5. int main()
  6. {
  7.   int n, result;
  8.  
  9.   scanf("%d", &n);
  10.  
  11.   result = add_digits(n);
  12.  
  13.   printf("%d\n", result);
  14.  
  15.   return 0;
  16. }
  17.  
  18. int add_digits(int n) {
  19.   static int sum = 0;
  20.  
  21.   if (n == 0) {
  22.     return 0;
  23.   }
  24.  
  25.   sum = n%10 + add_digits(n/10);
  26.  
  27.   return sum;
  28. }

The static variable sum is used and initialized to 0; its value will persist after function calls, i.e., it is initialized once when the function is called for the first time.