Java Program to Find Factorial of a Number Using Recursion

Here is a Java program to find factorial of a number using recursion. 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

Recommended Posts
Java Program to Find Factorial of a Number using For Loop
Java Program to Reverse a Number using Recursion
Java Program to Print Multiplication Table of Number
Java Program To Reverse Digits of a Number using While Loop
Java Program to Print Prime Numbers between 1 to 100
Java Program to Check Perfect Number or Not
Java Program to Find LCM and GCD of Two Numbers
Java Program to Convert Fahrenheit to Celsius
Java program to convert binary number to decimal number
Java Program to Check If a Year is Leap Year or Not
Java Program to calculate area and circumference of circle
All Java Programs