Problem with recurrsive return statement

• 12-08-2009, 12:21 AM
pachufir
Problem with recurrsive return statement
Hi I'm trying to create a program that uses a factorial method based on recursion, however there seems to be a problem.. i think it's because the program is returning the statement before it does it again, however it gives me problems if i try to put it in an else statement... Anybody know how i can fix this?

Code:

```import java.util.Scanner; public class Permutation {         public static void main(String[] args)         {                 Scanner input = new Scanner(System.in);                 System.out.println("Input a number");                 int number = input.nextInt();                                 int answer = factorial(number, 1);                                 System.out.println("Answer: " + answer);                         }         public static int factorial(int x, int total)         {                 if(x > 0)                 {                         total = total * x;                         x--;                         factorial(x, total);                 }                                 return total;                         } }```
• 12-08-2009, 01:33 AM
Fubarable
You never update total...
Code:

```  public static int factorial(int x, int total) {     if (x > 0) {       total = total * x;       x--;       total = factorial(x, total); // update total     }     return total;   }```
• 12-08-2009, 02:00 AM
pachufir
oh, ha, must have overlooked that... thanks a lot!
• 12-08-2009, 03:32 AM
Fubarable
of course i usually do something like,

Code:

```  public static int factorial2(int x) {     if (x > 0) {       return x * factorial2(x - 1);     } else {       return 1;     }   }```