Carlos Montiel
Carlos Montiel

Reputation: 301

Easy recursive factorial function

I'm testing many options in java so I want to do an easy recursive function in java.

I use console to execute the program, it receives a parameter but always when I try the recursion with any parameter that should be more than 1, it shows 0.

public class rec{
    public static void main (String[] args) {
        int h = 0;
        int numero = Integer.parseInt(args[0]);
        int factor = 0;

        if ( numero == 0 || numero == 1){
            System.out.println(1);
        } else {
            int xpi = factorial(numero-1);
            System.out.println(factor);
        }
    }

    public static int factorial (int n){
        System.out.println("lol");
        if(n==0) {
            return 0;
        } else{ 
            return n* (n-1);
        }
    }
}

Upvotes: 1

Views: 171

Answers (2)

Drazen Bjelovuk
Drazen Bjelovuk

Reputation: 5472

Your method is not recursive as it doesn't invoke itself. This would be an example of recursion:

public static int factorial(int n) {
    return n == 0 ? 1 : n * factorial(n-1);
}

Upvotes: 1

Alexey Chernov
Alexey Chernov

Reputation: 69

Take a look at these lines of your code:

int xpi = factorial(numero-1);
System.out.println(factor);

You put the result of function to xpi variable, but then you print factor variable. Printing xpi should work.

System.out.println(xpi);

Upvotes: 3

Related Questions