Write a c program in C to find the sum of digits of a number using recursion
Input number:1234
Output: Sum of digits: 10
Answers
Answer:
This is the required program for the question in C.
#include <stdio.h>
int sum(int n) {
if(n!=0)
return (n%10 + sum(n/10));
else
return 0;
}
int main()
{
int n;
printf("Enter a number - ");
scanf("%d",&n);
printf("Sum of the digits of %d is: %d",n,sum(n));
return 0;
}
Explanation:
Recursion is the process in which a function calls itself. Here, sum() is the recursive function.
Consider the sum block.
int sum(int n) {
if(n!=0)
return (n%10 + sum(n/10));
else
return 0;
}
If the number is - 123
Then, n!=0 is true.
The function returns n%10 + sum(n/10)
= 3 + sum(123/10)
= 3 + sum(12)
Again, 12 is not equal to 0. So,
= 3 + (12%10 + sum(12/10))
= 3 + 2 + sum(1)
Again, 1 is not equal to 0. So,
= 3 + 2 + (1%10 + sum(1/10))
= 3 + 2 + 1 +sum(0)
Now, the number becomes 0. So the sum becomes,
= 3 + 2 + 1 + 0
= 6
So, now the function returns 6. In this way, the sum of the digits of the number is calculated.