Welcome to the Java Programming Forums

The professional, friendly Java community. 21,500 members and growing!

The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.

>> REGISTER NOW TO START POSTING

# Thread: Quick Recursion question involving sum

1. ## 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.

```
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

2. ## Re: Quick Recursion question involving sum

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

3. ## Re: Quick Recursion question involving sum

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.

4. ## Re: Quick Recursion question involving sum

When I execute sum(256) it returns 13? How do you get 31?

5. ## 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.

6. ## 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.

7. ## The Following User Says Thank You to Norm For This Useful Post:

ManInTheMiddle (December 1st, 2012)

8. ## Re: Quick Recursion question involving sum

Cheers man. I'll give it a shot.

Much appreciated.