0

// this is a recursive function for finding the sum of digits in C language //I'm not getting any output in my IDE.

int dsum(int n)
{
    int a, r;
    r = n % 10;
    a = r + dsum(n / 10);
    return a;
}
int main()
{
    int a;
    a= dsum(12345);
    printf("%d",a);
    return 0;
}
3
  • 4
    everytime you enter dsum() you keep recursing forever and ever. There is no way for the funtion to terminate. Maybe add if (n == 0) return 0; See ideone.com/I3bJ9J Commented Oct 24, 2021 at 7:39
  • 1
    You'll probably get a stack overflow eventually. Commented Oct 24, 2021 at 7:39
  • Use hint by pmg. Also init your a and 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. Commented Oct 24, 2021 at 7:42

1 Answer 1

1

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;
}
Sign up to request clarification or add additional context in comments.

3 Comments

While this code may solve the question, including an explanation of how and why this solves the problem would really help to improve the quality of your post, and probably result in more up-votes. Remember that you are answering the question for readers in the future, not just the person asking now. Please edit your answer to add explanations and give an indication of what limitations and assumptions apply.
thanks!, now its working i cant believe i missed the base part
Glad I could help!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.