Quick Recursion question involving sum
Hi,
I have a recursive method to find the sum of a given number that's greater than 10 respectively.
Code Java:
static int sum(int n) {
if(n < 10) {
return n;
} else {
return sum(n/10) + (n % 10);
}
}
I know this splits the number up into lets say 256 was entered 2 + 5 + 6 = 13 the sum.
My question is how exactly does it split it up.
I only got this through keyboard bashing and I want to be able to see recursion in my head properly.
Many thanks,
Seán
Re: Quick Recursion question involving sum
Quote:
question is how exactly does it split it up.
print out the results of the two operators: % and / to see what they do to the number.
Then compare the results to the original number.
what is nbr/10
what is nbr % 10
Re: Quick Recursion question involving sum
Quote:
Originally Posted by
Norm
print out the results of the two operators: % and / to see what they do to the number.
Then compare the results to the original number.
what is nbr/10
what is nbr % 10
I understand how the div and mod works. What I'm having trouble with is when it comes in for the first time.
256 / 10 = 25
256 % 10 = 6
which is 31.
Re: Quick Recursion question involving sum
When I execute sum(256) it returns 13? How do you get 31?
Re: Quick Recursion question involving sum
No, when I run this code I get 13. The code is right I'm just finding it hard to understand the logic behind it.
I understand how it works (kind of) just what happens when it gets passed through first.
Re: Quick Recursion question involving sum
Add lots of println statements that show the execution flow and the values of the variables as they are used and passed. That should show you when the method is called and what the args are when it is called and what value it returns for each call. You will have to rework the code so you can print out what the method is going to return before it returns it.
Re: Quick Recursion question involving sum
Cheers man. I'll give it a shot.
Much appreciated.