1. Member
Join Date
Mar 2012
Posts
29
Rep Power
0

## Recursion adding the digits of an integer

Hey guys I was working on this practice problem from a website I solved it but I don't understand how it works. I have tried retracing it but it makes no sense to me. The point of the problem was to add the digits of an int recursively. (for example integer 123 = 3+2+1 = 6)
Java Code:
```public int sumDigits(int n)
{
if(n<= 9)
return n;
return sumDigits(n/10)+sumDigits(n%10);
}```
I do understand that n/10 removes the rightmost digit and n%10 removes the leftmost digit.
Thanks.

2. ## Re: Recursion adding the digits of an integer

Use a piece of paper to work through the steps that the code does when it executes.

3. ## Re: Recursion adding the digits of an integer

Suppose I have a very intelligent but very shy friend; he can do what you want (add the digits of a number); I am just a bluffing guy who also claims he can do it; aamof, I can only add one single digit to a number; basically, this is me:

Java Code:
```int meBluffing(int number) {
if (number < 10) return number;
return myShyFriend(number/10)+number%10;```
What I basically do is take the last digit from the number, let my friend do the hard work (if there is anything left to do) and add my last digit to what my friend returned. Here's the clue: I'm schizophrenic: I have no friend, I made him up; so this is basically me:

Java Code:
```int meBluffing(int number) {
if (number < 10) return number;
return meBluffing(number/10)+number%10;```
As you can see from the above, this method is a recursive method; basically identical to your method (it has another name, but that isn't relevant).

kind regarrds,

Jos