# Recursion issues?

Page 1 of 1

## 5 Replies - 988 Views - Last Post: 11 March 2013 - 11:46 PM

Reputation: 4
• Posts: 61
• Joined: 23-October 12

# Recursion issues?

Posted 11 March 2013 - 06:11 PM

OK, so i want to point out that i am not asking for code. i have an homework assignment that i am very confused on how to start. I am in basic Javascript and i need to make a recursion function that does the following.I need to write a recursive function that returns the sum of the digits of an integer.
For example

If x is 234, the function should return 2 + 3 + 4, that is, 9.
If x is 12, the function should return 1 + 2, which is 3.
If x is 39, the function should return 12.
If x is negative, ignore the minus sign. For example, -12 and 12 both return 3.

Now i cant use a while or for loop so i am just lost. is there a method that i might not know about that i can research?

I am just looking to see if there might be something out there to help me before i put up my code and let it define my question. />

Is This A Good Question/Topic? 0

## Replies To: Recursion issues?

### #2 macosxnerd101

• Games, Graphs, and Auctions

Reputation: 12241
• Posts: 45,327
• Joined: 27-December 08

## Re: Recursion issues?

Posted 11 March 2013 - 06:13 PM

Think about division by 10 and modulus by 10 to get each digit. Then recurse for the smaller number.

Reputation: 4
• Posts: 61
• Joined: 23-October 12

## Re: Recursion issues?

Posted 11 March 2013 - 06:16 PM

So when ever i run my code, i don't get the correct output.
```function dispprompt()
{

var prompted = prompt("Please enter an integer:");
var num = parseInt(prompted);

}

{
var num = num;
num = Math.abs(num);

if (num <= 9)
{

num2 = num % 10
num += num2;
return num;

}

else
{

num = Math.floor(num/10);

}

}

```

### #4 macosxnerd101

• Games, Graphs, and Auctions

Reputation: 12241
• Posts: 45,327
• Joined: 27-December 08

## Re: Recursion issues?

Posted 11 March 2013 - 06:22 PM

In the future, please be more specific as to the specific problems or errors you are encountering.

If the digit <= 9, just return the digit. Otherwise, return (num % 10) + the recursive call for num/10.

Reputation: 4
• Posts: 61
• Joined: 23-October 12

## Re: Recursion issues?

Posted 11 March 2013 - 11:38 PM

Ahhh, Thanks that makes more things clear. thank you.

### #6 macosxnerd101

• Games, Graphs, and Auctions

Reputation: 12241
• Posts: 45,327
• Joined: 27-December 08

## Re: Recursion issues?

Posted 11 March 2013 - 11:46 PM

Glad I could help!