Factorial Using Recursion In Java

Factorial Using Recursion In Java

In this article, we are discussing how to write a program to calculate the Factorial Using Recursion In Java. Recursion is the type of function which calls another function or calls itself. There are two types of recursion :

1. Direct Recursion: Direct recursion is the type of recursion in which the function calls itself again and again.

2. Indirect Recursion: Indirect Recursion is a type of recursion that calls another function.

We are providing all the programs related to java. If you are interested then click here.

Factorial Using Recursion In Java:

In this section, we will be discussing the logic of the program and how to calculate the factorial of any number in java using recursion. Simply, use the Scanner class to take the number from the user then pass this number as an argument and store their upcoming result in the result variable. After passing the number as an argument now the compiler will move to the function definition.

We use the fourth type of function in our program that returns some value in the main. The number sent from the main will be received by an integer type variable ‘n’. In the function definition, we know that the factorial of 1 and 0 is always 1 so, we put the condition in the if statement. If the number is equal to 1 or less than 0 then return 1.

And else return the product of the number and factorial of number -1. And after this, it executes the number until the number will not become 1 and send the result to the main in the result variable that we declared earlier in the program then simply print the result (that is the factorial of the given number). So, this was the whole logic of the program.

Source Code:

import java.util.Scanner;

public class Recursion {
    int factorial(int n){
            return 1;
            return n*factorial(n-1);

    public static void main(String[] args) {
        Recursion obj = new Recursion();
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter Any Number : ");
        int number = sc.nextInt();
        int result = obj.factorial(number);
        System.out.println("Factorial Of "+number+" is "+result);


Factorial Using Recursion In Java





From the above program, we conclude how to write a java program to calculate the factorial of any number.


Leave a Reply

Your email address will not be published. Required fields are marked *