I am trying to make a recursive function which should return the sum of digits. The function should have only one argument. So far I have this;
public int sumDigits(int n) {
if(n%10 == n) // last digit remains
return n;
else{
int rightdigit;
rightdigit = n%10; // taking out the right most digit
return rightdigit + (n/10); // adding it to everything on left
}
}
The function works for some values, specifically 2 digit numbers. But It gives out really odd values for some numbers like 730 which comes out to be 73 when it should be 10.
I have worked it out on paper but cant figure out where I am going wrong. Any help would be much appreciated.
You aren't actually recursing. You've setup your base case, but when solving a problem recursively you should have code within the function that calls the function itself.
So you're missing a line that calls
sumDigits
, with a smaller argument.Consider two important parts of a recursive soutlion:
Note that your problem fits this pretty well: you've got 2 cases in an if/else. Your base case is set up nicely, now in the other branch you'll want to actually recurse. It should be very obvious to you where to put the call to
sumDigits
.