Results 1 to 4 of 4
  1. #1
    pachufir is offline Member
    Join Date
    Dec 2009
    Posts
    3
    Rep Power
    0

    Default 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?

    PHP 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;
    		
    	}
    }

  2. #2
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,315
    Blog Entries
    1
    Rep Power
    26

    Default

    You never update total...
    Java Code:
      public static int factorial(int x, int total) {
        if (x > 0) {
          total = total * x;
          x--;
          total = factorial(x, total); // update total
        }
        return total;
      }

  3. #3
    pachufir is offline Member
    Join Date
    Dec 2009
    Posts
    3
    Rep Power
    0

    Default

    oh, ha, must have overlooked that... thanks a lot!

  4. #4
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,315
    Blog Entries
    1
    Rep Power
    26

    Default

    of course i usually do something like,

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

Similar Threads

  1. insert statement return problem in ibatis
    By dheerajsea123 in forum JDBC
    Replies: 1
    Last Post: 05-20-2010, 11:22 AM
  2. Help with Recursion and return statement
    By nicolek808 in forum New To Java
    Replies: 3
    Last Post: 09-10-2009, 11:02 AM
  3. problem while using return statement
    By shaluchandran in forum New To Java
    Replies: 10
    Last Post: 12-12-2008, 07:29 PM
  4. there is no return statement
    By gabriel in forum New To Java
    Replies: 17
    Last Post: 12-03-2008, 05:55 PM
  5. [SOLVED] return statement
    By Nakira in forum New To Java
    Replies: 8
    Last Post: 11-13-2008, 12:00 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •