# Java recursion problem

Discussion in 'OT Technology' started by an0nymous, Nov 8, 2005.

1. ### an0nymousAnon E. Mouse

Joined:
Jan 7, 2005
Messages:
710
0
I'm supposed to write a recursive method to count the sum of the digits in an integer. For example, 431 should return 8 (4 + 3 + 1).

The method in question is sumDigits()

As the code is now, it adds a digit to what is returned each time it adds something
so for 431 it returns 478 - the 7 is from (4 + 3) and the 8 is from (4 + 3 + 1)

I know it's something simple, but for the life of me I can't figure out what I'm doing wrong. Any help would be appreciated.

Here's the method that needs work:
Code:
```[B]     public static int sumDigits(int num)
{
if (num < 10)
return (num);
else
return (num + sumDigits(num / 10));
}[/B]```
And here's the whole program:

Code:
```import java.util.Scanner;

public class DigitPlay
{
public static void main (String[] args)
{
int num; //a number
Scanner scan = new Scanner(System.in);

System.out.println ();
System.out.print ("Please enter a positive integer: ");
num = scan.nextInt ();

if (num <= 0)
System.out.println ( num + " isn't positive -- start over!!");
else
{
// Call numDigits to find the number of digits in the number
// Print the number returned from numDigits
System.out.println ("\nThe number " + num + " contains " +
+ numDigits(num) + " digits.");
System.out.println("The sum of the digits in " + num + " is " +
sumDigits(num) + ".");
System.out.println ();
}
}

// -----------------------------------------------------------
// Recursively counts the digits in a positive integer
// -----------------------------------------------------------
public static int numDigits(int num)
{
if (num < 10)
return (1);
else
return (1 + numDigits(num/10));
}

// recursively count the sum of the digits in a positive integer

[B]     public static int sumDigits(int num)
{
if (num < 10)
return (num);
else
return (num + sumDigits(num / 10));
}[/B]
}```

Last edited: Nov 8, 2005
2. ### skinjobActive Member

Joined:
Jan 6, 2001
Messages:
2,337
0
Location:
Aztlán
You're not breaking up num into its digits.
After the first iteration, you're returning 431 + sumdigits(43).
After the next go around, you're returning 43 + sumdigits(4).
And finally, you return 4. Sum those up you get 478.

You should use the modulo operator to break down num into it's digits.
return num % 10 + sumdigits(num / 10);

Joined:
Jan 7, 2005
Messages:
710
0
bump

Joined:
Jan 7, 2005
Messages:
710