Java Program to Find Factorial of a Number Using Recursion

To understand this example, you should have the knowledge of the following Java programming topics:


The factorial of a positive number n is given by:

factorial of n (n!) = 1 * 2 * 3 * 4 * ... * n

The factorial of a negative number doesn't exist. And the factorial of 0 is 1.

You will learn to find the factorial of a number using recursion in this example. Visit this page to learn, how you can find the factorial of a number using loop.

Example: Factorial of a Number Using Recursion

public class Factorial {

    public static void main(String[] args) {
        int num = 6;
        long factorial = multiplyNumbers(num);
        System.out.println("Factorial of " + num + " = " + factorial);
    }
    public static long multiplyNumbers(int num)
    {
        if (num >= 1)
            return num * multiplyNumbers(num - 1);
        else
            return 1;
    }
}

Output

Factorial of 6 = 720

Initially, the multiplyNumbers() is called from the main() function with 6 passed as an argument.

Since 6 is greater than or equal to 1, 6 is multiplied to the result of multiplyNumbers() where 5 (num -1) is passed. Since, it is called from the same function, it is a recursive call.

In each recursive call, the value of argument num is decreased by 1 until num reaches less than 1.

When the value of num is less than 1, there is no recursive call.

And each recursive calls returns giving us:

6 * 5 * 4 * 3 * 2 * 1 * 1 (for 0) = 720

Before we wrap up, let’s put your knowledge of Java Program to Find Factorial of a Number Using Recursion to the test! Can you solve the following challenge?

Challenge:

Write a function to calculate the factorial of a number.

  • The factorial of a non-negative integer n is the product of all positive integers less than or equal to n.
  • Return the calculated factorial of the input num.
  • For example, if num = 5, the expected output is 120 (i.e., 5 * 4 * 3 * 2 * 1 = 120).
Did you find this article helpful?

Our premium learning platform, created with over a decade of experience and thousands of feedbacks.

Learn and improve your coding skills like never before.

Try Programiz PRO
  • Interactive Courses
  • Certificates
  • AI Help
  • 2000+ Challenges