Anony Mous
Anony Mous

Reputation: 23

Java Stack Overflow in recursion with pre-incrementor

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!

Upvotes: 0

Views: 57

Answers (2)

JBALI
JBALI

Reputation: 89

Make these changes to avoid stack overflow`

  public static int factorial(int n) {
   int result;
   if (n == 1)
        return 1;
       result = factorial(n-1)*n
       return result }

Upvotes: 0

Eran
Eran

Reputation: 394106

Of course it doesn't work. factorial(n--) has the same effect as factorial(n), since it passes the value to the recursive call before decrementing it, and the decremented value is never used, resulting in endless recursion or at least until stack overflows.

When you use pre-increment, on the other hand, the recursive call gets n-1, and the recursion works.

Upvotes: 6

Related Questions