A recursion function should always have a base case as a final return, in this case it's when n equals 0, which means all digits were summed (when msb digit is divided by 10 the result is 0).
Then you'll have the return which will call the function with the result of the current lsb digit (or right most digit) + the result of the function with the input of n/10
int dsum(int n)
{
if (n == 0) {
return 0;
}
return n % 10 + dsum(n / 10);
}
int main()
{
int a;
a = dsum(12345);
printf("%d",a);
return 0;
}
BTW, I also suggest looking into tail recursion:
https://en.wikipedia.org/wiki/Tail_call
In this scenario, it might look like that:
int dsum_tail_recursion(int n, int sum)
{
if (n == 0) {
return sum;
}
return dsum_tail_recursion(n/10, n%10 + sum)
}
int main()
{
int a;
a = dsum_tail_recursion(12345, 0); // 0 is the sum start value
printf("%d",a);
return 0;
}
dsum()you keep recursing forever and ever. There is no way for the funtion to terminate. Maybe addif (n == 0) return 0;See ideone.com/I3bJ9Jaand make sure that you flush for output. For future questions please study and apply the concept of making a minimal reproducible example. The``typo indicates that you did not fully get it yet.