0

Tried writing a recursive function for digit sum in c++ ; ended up getting the last digit instead. Can anyone suggest fixes.. '''

#include<iostream>
using namespace std;

int dsum (int n, int sum)
{
    if(n>0)
    {
        sum = sum + (n%10);
        n = n/10;
        return(n ,sum);
    }
    else return sum;

}

int main()
{
    int i = 345;
    int s = dsum (i,0);
    cout<<"Sum is "<<s;
    return 0;
}

'''

1 Answers1

0

You didn't call the recursion as seen in here:

int dsum (int n, int sum)
{
    if(n>0)
    {
        sum = sum + (n%10);
        n = n/10;
        return(n ,sum); // <-- this line
    }
    else return sum;

}

Notice you return(n ,sum); instead of return dsum(n ,sum);. return(n ,sum); fist evaluates the left operand: n and then the right operand: sum. Since there's nothing to evaluates, it will returns the result of the right operand, which is sum.