C Program to find sum of digits of a number

In order to find sum of digits of a number, this C program separates each digit of number using modulus 10 and then sums up each digit to get result. For example if we consider the given number as 325 then modulus 10 of 325 gives 5. So in order to get digit in tenth’s place i.e., 2 in the given number we divide the number by 10 so that number becomes 32 and then we apply modulus 10 again to get 2. This process is done until there are no digits left in the given number. This condition is checked using n>0 in while loop. C Program to find sum of digits of a number

Source code:

int main()
	int n, s=0, r;
	printf("\n Enter the Number :");
	scanf("%d", &n);                         //Step 1
	while(n>0)                               //Step 5
		r=n%10;                             // Step 2
		s=s+r;                             // Step 3
		n=n/10;                            // Step 4    
	printf("\nSum of digits :%d", s);
	return 0;

Sample test cases:

 1. Enter the number : 325
   Sum of digits : 10

2. Enter the number : 45689
   Sum of digits : 32

3. Enter the number : 987456
   Sum of digits : 39


Step 1: Program reads a number from the user using scanf() function. Step 2: The remainder of a given number when divided by 10 is found using modulus operator and is stored in variable ‘r’. Step 3: This r value is added to sum to get sum of digits of a given number. Step 4: The given number is divided by 10 to remove last digit from the given number. Step 5: Step 2 to Step 4 are done recursively until n>0.

More Content : Explore More