Well, I've made a program that can find the factorial of a number trough recursion. It works alright, but there is a problem with incrementing. See, if I write the program like this, it does'nt work! -
package programming.tutorialnext;
import java.util.Scanner;
public class Factorial_Recursion {
public static int factorial(int n) {
if (n == 1) {
return n;
} else {
return n * factorial(n--);
}
}
public static void main(String[] args) {
Scanner bucky = new Scanner(System.in);
int n;
System.out.print("Enter a number for it's factorial :");
n = bucky.nextInt();
System.out.print("This is it's factorial : " + factorial(n));
}
}
It says for some reason the Stack is Overflowing even if the no. = 3! But, if I use the the pre-incrementor like this : --n at the top, it works fine!
n * factorial(--n);instead ofn * factorial(n--);