简体   繁体   中英

I'm not getting any output in recursive function (C language)

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM