首页 > 解决方案 > I'm not getting any output in recursive function

问题描述

// 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;
}

标签: crecursion

解决方案


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;
}

推荐阅读