Results 1 to 4 of 4
- 12-07-2009, 11:21 PM #1
Member
- Join Date
- Dec 2009
- Posts
- 3
- Rep Power
- 0
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; } }
-
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; }
- 12-08-2009, 01:00 AM #3
Member
- Join Date
- Dec 2009
- Posts
- 3
- Rep Power
- 0
oh, ha, must have overlooked that... thanks a lot!
-
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
-
insert statement return problem in ibatis
By dheerajsea123 in forum JDBCReplies: 1Last Post: 05-20-2010, 10:22 AM -
Help with Recursion and return statement
By nicolek808 in forum New To JavaReplies: 3Last Post: 09-10-2009, 10:02 AM -
problem while using return statement
By shaluchandran in forum New To JavaReplies: 10Last Post: 12-12-2008, 06:29 PM -
there is no return statement
By gabriel in forum New To JavaReplies: 17Last Post: 12-03-2008, 04:55 PM -
[SOLVED] return statement
By Nakira in forum New To JavaReplies: 8Last Post: 11-12-2008, 11:00 PM


LinkBack URL
About LinkBacks
Reply With Quote
Bookmarks