Java Program to Find Factorial of a Number Using Recursion

In this program, you’ll learn to find and display the factorial of a number using a recursive function in

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.

Example: Factorial of a Number Using Recursion

  1. public class Factorial {
  2. public static void main(String[] args) {
  3. int num = 6;
  4. long factorial = multiplyNumbers(num);
  5. System.out.println("Factorial of " + num + " = " + factorial);
  6. }
  7. public static long multiplyNumbers(int num)
  8. {
  9. if (num >= 1)
  10. return num * multiplyNumbers(num - 1);
  11. else
  12. return 1;
  13. }
  14. }

When you run the program, the output will be:

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