Java Program to find out the factorial of a number using recursion


March 16, 2022, Learn eTutorial
1010

Here we are explaining how to write a java program to find out the factorial of a number. So first we have to read the number from the user. Then we will call the function Fact() to find out the factorial of the number.

How to find out the factorial of a number n?

We can find out the factorial of a number n by using the formula

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

Factorial of a number n is the product of all positive integers less than or equal to n.the factorial of a number n is denoted by n!.

Example:Factorial of 5 is ,5!=1 * 2 * 3 * 4 * 5

                                            =120  

How to implement the java program to find out the factorial of a number?

First, we have to declare the class Fact. Then declare the integer variables n,f. Create an object of the scanner class sc to read the integer number. Then read the integer number from the user into the variable n. Create an object of the class Fact as Fact obj=new Fact(). Then call the recursive function fact(n) a recursive function is a function, which calls its self during its execution.

In the fact(int y) function, it checks the parameter y>1, if true then it will call the function itself as fact(y-1) until y becomes 1.Then it will return the factorial of the number. So we can display the factorial of number n as f.

ALGORITHM

STEP 1: Declare the class Fact with a public modifier.

STEP 2: Open the main() to start the program, Java program execution starts with the main()

STEP 3: Declare the integer variable n,f.

STEP 4: Create the object of the scanner class as sc.

STEP 5: Read the integer number into the variable n.

STEP 6: Create the object of the class Fact as obj.

STEP 7: Call the function fact(n) as f=obj.fact(n).

STEP 8: Display the factorial of the number as f.

Function int fact(int y)

STEP 1: Check if y>1 then return y*fact(y-1)

STEP 2:Return 1.

 

Java Source Code

                                          import java.util.Scanner;
public class Fact {
    public static void main(String[] args) {
        int n, f;
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter any integer number:");
        n = sc.nextInt();
        Fact obj = new Fact();
        f = obj.fact(n);
        System.out.println("Factorial of " + n + " is " + f);
    }
    int fact(int y) {
        if (y > 1) {
            return (y * fact(y - 1));
        }
        return 1;
    }
}
                                      

OUTPUT

Enter any integer number:5

Factorial of 5 is 120