Reputation: 19
I am trying to understand the recursive methods in Java and tried this simple method to calculate a factorial. Somehow it doesn't work. Can someone tell me why?
public class FactorialRecursive extends ConsoleProgram {
public void run() {
println("This program calculates the factorial of an integer n.");
int n = readInt("Please insert n: ");
int result = factorial(n);
println("The factorial of " + n + " is " + result);
}
private int factorial(int n) {
int total;
if (n == 1) total = 1;
total = n * factorial(n - 1);
return (total);
}
}
Upvotes: 1
Views: 2169
Reputation: 22171
Replace the line:
if (n==1) total = 1;
by:
if (n==1) return 1;
Otherwise, you'll loop infinitely.
Your method would be:
private int factorial(int n) {
return n==1 ? 1 : n * factorial (n-1);
}
Upvotes: 2
Reputation: 22890
The issue is that you dont stop when you find your base case
if (n==1) total = 1;
Rather do
if (n==1) return 1;
Upvotes: 2
Reputation: 36630
You are not terminating your recursion. Try
if (n==1) total = 1;
else total = n * factorial (n-1);
Upvotes: 3
Reputation: 726579
This is because your base case (n == 1
) does not return right away.
You only assign total
, but do not return: instead, you go with n * factorial(n-1)
again, entering into infinite recursion.
Fix by replacing with
if (n==1) return 1;
or adding an else
:
if (n==1) total = 1;
else total = n * factorial (n-1);
Upvotes: 4