# Recursion?

Discussion in 'OT Technology' started by BigEZ, Sep 6, 2008.

1. ### BigEZNew Member

Joined:
Apr 25, 2007
Messages:
3,017
0
Location:
Amarillo
I've got an assignment for my second programming class. This is the first time I've been introduced to the idea of recursion, and I'm having trouble finding a start. This will be done in Java, but if some one could point me in the right direction with the algorithm, I can handle that part just fine.

The problem asks that I write a program that takes an integer argument (non negative) and return the sum of the digits that make up the number. It must be done recursively.

Any help is appreciated.

2. ### PeyompNew Member

Joined:
Jan 11, 2002
Messages:
14,017
0
If you're having trouble, email the professor. Read the textbook. Thats your start.

Joined:
Jan 11, 2002
Messages:
14,017
0
4. ### ge0New Member

Joined:
Oct 31, 2005
Messages:
8,398
0
Location:
JERSEY
all recursion is in your sense is recalling the same function from within the function

5. ### whupI wish you had children and.. so that I could step

Joined:
Feb 12, 2007
Messages:
1,603
0
What it's actually asking for is the factorial of a number, calculated with a recursive method. You should be able to find what you need with those terms.

Joined:
Feb 12, 2007
Messages:
1,603
0

7. ### PeyompNew Member

Joined:
Jan 11, 2002
Messages:
14,017
0
This thread is a piece of shit.

8. ### Sexual VanillaNew Member

Joined:
May 23, 2005
Messages:
6,305
0
Location:
South Carolina

Joined:
Jan 11, 2002
Messages:
14,017
0
10. ### Sexual VanillaNew Member

Joined:
May 23, 2005
Messages:
6,305
0
Location:
South Carolina
11. ### BigEZNew Member

Joined:
Apr 25, 2007
Messages:
3,017
0
Location:
Amarillo
Okay, I did some research and game up with a solution to the initial question, which is shown below as digitSum(num). Now I need to write an additional function, digitalRoot(num) which will continue the process, for example:

digitsum takes input 444, and outputs 12
digitalRoot will continue and add the digits of 12 and output 3

My initial thought was to use a while loop and while num>10 (or more than one digit), it will repeat the process and output a single digit. However, I can't figure out how to do so. The function can only return num, but I need an additional variable to do all of the math.

I'm sure I'm overlooking something .. Any help would be appreciated.

Code:
```public class Functions {
public static int digitSum(int num){
if (num<10)
return (num);
else
return ((num%10) + digitSum(num/10));
}

public static int digitalRoot(int num){
if (num<10)
return (num);
while (num>=10){
int temp = ((num%10) + digitalRoot(num/10));
}
return temp;
}
}
```

12. ### skinjobActive Member

Joined:
Jan 6, 2001
Messages:
2,290
0
Location:
Aztlán
You're overlooking code reuse. By your description, digitRoot is just calling digitSum twice.

Joined:
Apr 25, 2007
Messages:
3,017