I have the below recursive function to compute factorial of a number. The program works fine except when I remove the if condition. Can someone explain why?
This is the code that works fine --
public static long factUsingRecursion(int number) {
if (number == 1) {
return 1;
} else {
return number * factUsingRecursion(number - 1);
}
}
Without the if condition (Code that throws the error),
public static long factUsingRecursion(int number) {
return number * factUsingRecursion(number - 1);
}
I get the stack overflow error.
Exception in thread "main"
java.lang.StackOverflowError
atbirst.FactorialUsingRecursion.factUsingRecursion(FactorialUsingRecursion.java:10)
Request experts to please advise me why this is the case?