C Program Sum of Digit of given Number

C Program Sum of Digit of given Number

This program logic is based on looping structures and mod operator. mod operator % returns the remainder after division of two integers.

  1. Input number of integer type
  2. Obtain its remainder by dividing it by 10.
  3. Add remainder in sum variable.
  4. Divide the given number by 10
  5. Repeat same from step 2 till given number become zero.
  6. Print the output from sum variable and exit.
#include<stdio.h>
int main()
{
        int r,num,sum;

	printf("\nEnter number: ");
	scanf("%d",&num);

	sum=0;  //to hold output
	while (num>0)
	{
		while(num>0)
		{
		r=num%10;  
		sum=sum+r;
		num=num/10;
		}
		
		printf("\n\tSum= %d\n",sum);
		if(sum>9)
		{
			num=sum;
			sum=0;
		}
	}
	printf("\n--------------------digitalpadm.com\n");

return 0;
}

In above example, variable num to hold given number, variable r to hold remainder after mod operation. initialize variable sum to zero. 

suppose, value of num=368

r= num % 10 ; it returns the remainder after division operation.  i. e  8

sum = sum + r;   add the value of r variable to sum , as sum of digits

num=num / 10;  returns the quotient after division operation. i.e 36

repeat same steps till n is greater than zero. 

if sum is > 9 i.e it is two digit answer so assign value of sum variable to num variable , and repeat same steps. till value of sum become single digit.

SUM-OF-DIGIT.c (40 downloads)
OUTPUT
output-c-programsum-of-digit
output-c-program-sum-of-digit