Home > Back-end >  why is this code not working without return statement before factorial [closed]
why is this code not working without return statement before factorial [closed]

Time:09-29

class FactorialRecursive 
{    
    public static int factorial(int a,int i)
    {  
       i=i*a;
       a--;
       
       if (a>1)
        {
          return factorial(a,i);    
        }
        return i;
    }
    public static void main(String[] args) 
    {  
       int n=5;
       int res = factorial(n,1);
       System.out.println("The factorial of " n " is " res);
    }
}

CodePudding user response:

Not sure why you're even using two parameters for a recursive factorial method. You only need one parameter, your n value.

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

CodePudding user response:

You ask why factorial(a,i); alone doesn't work, and why you need return factorial(a,i);

Your question assumes that i=i*a; and a--; will be seen from the calling function. This is not the case.

Instead, arguments are private to each individual invocation of the function. You may already be aware of this in the non-recursive case:

class Test {
  static void square(int n) {
    n = n*n;
    System.out.println("squared so that n="   n);
  }

  public static void main(String[] args) {
    int n=42;
    square(n);
    System.out.println("after the function is invoked, n="   n);
  }
}

this outputs

squared so that n=1764
after the function is invoked, n=42

because square's n is not the same as main's n.

The exact same is true for each invocation of factorial. Even though it's the same function, each invocation will have its own copy of n and i stored on the stack, and when you return, the previous invocation will still use its old values.

This is why you can't rely on a recursive call modifying local variables, and instead have to return a value to the caller via return.

CodePudding user response:

Java passes a copy of the value as an argument when calling the method. You can't update it within a method. But if you can update the second argument i, you don't need return.

For example

public static int factorial(int a, int[] i) {
    i[0] = i[0] * a;
    a--;

    if (a > 1) {
        factorial(a, i);
    }
    return i[0];
}

public static void main(String[] args) {
    int n = 5;
    int res = factorial(n, new int[] {1});
    System.out.println("The factorial of "   n   " is "   res);
}

output:

The factorial of 5 is 120
  • Related