Java Program to Find Factorial of a Number Using Recursion

  • Java program to find factorial of a number using recursion.
  • Recursive algorithm to find value of factorial of any number.

We have to write a recursive function in Java to calculate factorial of a number. he factorial of a integer N, denoted by N! is the product of all positive integers less than or equal to n.

N! = 1 x 2 x 3 x 4....x (N-2) x (N-1) x N

We can use recursion to calculate factorial of a number because factorial calculation obeys recursive sub-structure property.
Let getfactorial(N) is a function to calculate and return value of N!. To find factorial(N) we can first calculate factorial(N-1) then multiply it with N.

getfactorial(N) = getfactorial(N-1) x N
N! = (N-1)! x N
N! = 1 x 2 x 3 x 4....x (N-2) x (N-1) x N

Java program to find factorial of a number using recursion

package com.tcc.java.programs;

import java.util.*;

public class FactorialRecursion {
    public static void main(String args[]) {
        int num, factorial = 1, i;
  
        Scanner in = new Scanner(System.in);
        System.out.println("Enter an Integer");
        num = in.nextInt();
        factorial = getfactorial(num);
        
        System.out.println("!" + num + " = " + factorial);
    }

    public static int getfactorial(int num) {  
        if (num <= 1)
            return 1;
        return num * getfactorial(num-1);
    }
}
Output
Enter an Integer
6
!6 = 720