Search code examples
javarecursionfactorial

How do I print factorials without using a loop?


I made a recursive method to calculate factorials, but in the main method I have used a for loop to calculate the list of factorials. Is there a way to calculate a list of factorials without using a loop in the main method?

Code:

public class FactInt {
    public static void main(String[] args) {
        for (int n = 1; n < 11; n++)
            System.out.println(factorial(n));
    }
    //Calculates the factorial of integer n
    public static int factorial(int n) {
        if (n == 0)
            return 1;
        else 
            return n*factorial(n-1);
    }
}

Solution

  • It depends on exactly what you mean by "calculate a list", but this prints the same thing:

    public static void main(String[] args) {
        factorial(10);
    }
    //Calculates the factorial of integer n
    public static int factorial(int n) {
        if (n == 0)
            return 1;
        else {
            int newVal = n*factorial(n-1);
            System.out.println(newVal);
            return newVal;
        }
    }