Reputation: 162
I wrote a java recursive function to get sum of a number as follows, and the sum should be single digit as well.the problem i am facing here is it should return the else part at the end where as it is giving the after if else condition return statement:
static int recSum(int n){
int sum = 0;
while(n!=0){
sum += n%10;
n = n/10;
}
if(sum>9) {
recSum(sum);
}
else {
return sum;
}
return sum ;
}
Let us say n = 12345 so at the end it needs to return 5 where as it is returning 14. However it is going to the else part but the correct value is not returning. I got the solution with the ternary operator without else loop. but would like to what is the reason for this i am getting the previous sum of 14 rather 5 (5 comes from 14 = 1+4)
Appreciate the response on this
Upvotes: 0
Views: 69
Reputation: 2802
This is an iterative way (NOT a good way to build recursion in your program)
while (n != 0) {
sum += n % 10;
n = n / 10;
}
This is the correct recursive way and works even for 0 and negative numbers.
static int recSum(int n) {
int sum = 0;
sum = sum + (n % 10);
n = n / 10;
if (n != 0) {
return sum + recSum(n);
} else {
return sum;
}
}
Upvotes: 0
Reputation: 64
When this function gets to the if statement and calls the function again the 15 is saved on the stack until the current call is finished, when the current call is finished the previous answer was 15 so it's returning that because you dont modify it in anyway after it gets returned.
Upvotes: 0
Reputation: 937
The change you should do is fairly simple: you should remove the last return
statement and just return the result of recursive call:
static int recSum(int n){
int sum = 0;
while(n!=0){
sum += n%10;
n = n/10;
}
if(sum>9) {
return recSum(sum);
}
else {
return sum;
}
}
Upvotes: 1