C Program to Find the Sum of all Digits of a Number

Here we’ll see how to write a C program to find the summation of all digits in a number. For example, the sum of the digits of 43652 is 20 (4+3+6+5+2)

#include <stdio.h>

int sum_digits(int n) {
    int sum = 0;
    while(n) {
	    sum += (n % 10);
	    n /= 10;
	}
	return sum;
}

int main()
{
	int n = 0;
    printf("Enter an integer: ");
    scanf("%d", &n);
    
    printf("Sum of all digits of %d is %d.\n", n, sum_digits(n));
    return 0;
}

The sum_digits() function returns sum of all digits of the input number n. It has a loop. In every iteration it gets the last digit by doing modulo operation by 10 (n%10) and adds that digit to sum. It removes the last digit by doing the div operation by 10. (n/10). The loop terminates when n becomes 0.

Here is the output of the program.

Enter an integer: 43652
Sum of all digits of 43652 is 20.

Recursive Version

We can change the sum_digits() function to recursive one.

int sum_digits(int n) {
    int rem = n%10;
    
    if(rem == 0) return n;
    return rem + sum_digits(n/10);
}

If the number is a single digit number, rem (n%10) will be zero. So the sum would be the number itself. If the number is a multi-digit number, then rem will be the last digit. So some of all digits would be rem (last digit) plus some of all digits of the remaining number except the last digit. We can get the remaining number except the last number by doing div operation by 10. The recursive call of sum_digits() will give the sum of that number.

Author: Srikanta

I write here to help the readers learn and understand computer programing, algorithms, networking, OS concepts etc. in a simple way. I have 20 years of working experience in computer networking and industrial automation.


If you also want to contribute, click here.

2 thoughts on “C Program to Find the Sum of all Digits of a Number”


    1. #include <stdio.h>

      int sum_digits(char *s) {
      if (s[0] == '\0') return 0;
      return (s[0] - '0') + sum_digits(s + 1);
      }

      int main()
      {
      char s[64];
      printf("Enter an integer: ");
      gets(s);

      printf("Sum of all digits of %s is %d.\n", s, sum_digits(s));
      return 0;
      }

      Here the input is read as string instead of integer. The recursive function is modified accordingly.

Leave a Reply

Your email address will not be published. Required fields are marked *

0
0
0
1
0
1