0

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!

2
  • 3
    you sorta asked and answered the question at the same time... Commented Jan 11, 2015 at 6:36
  • Use n * factorial(--n); instead of n * factorial(n--); Commented Jan 11, 2015 at 6:40

2 Answers 2

6

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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 }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.