Home »
Code Snippets »
C/C++ Code Snippets
C program to find sum of all digits until sum is not in single digit
This program is asked by kalyani shevale through comment on 18/12/2016.
Question
I want one program code
input is an only integer value and output will be displayed only one digit in c
e g
input int a=8999
8+9+9+9=35
3+5=8
Answer
Here, we are writing this code to calculate sum of all digits until sum is not in single digit in c programming language.
For example:
If number is 8999 the sum will be 8+9+9+9 = 35 = 3+5 = 8
This program is implementing by using recursion function, the function calculateDigits() is calling recursively until sum is not less than 10.
#include <stdio.h>
int calculateDigits(int num)
{
int sum=0;
while(num!=0)
{
sum+=(num%10);
num/=10;
}
if(sum>=10)
calculateDigits(sum);
else
return sum;
}
int main()
{
int n,sum;
printf("Enter any positive integer number: ");
scanf("%d",&n);
if(n<0)
{
printf("Invalid input!!!\n");
return -1;
}
sum=calculateDigits(n);
printf("Sum of digits is: %d\n",sum);
return 0;
}
Output
First run:
Enter any positive integer number: 8999
Sum of digits is: 8
Second run:
Enter any positive integer number: 12345
Sum of digits is: 6