Java program to find the factorial of a given number using recursion


Recursion is the process of repeating items in a self-similar way. In programming languages, if a program allows you to call a function inside the same function, then it is called a recursive call of the function.

Following is an example to find the factorial of a given number using a recursive function.

import java.util.Scanner;
public class ab21_FactorialUsingRecursion {
   public static long factorial(int i) {
      if(i <= 1) {
         return 1;
      }
      return i * factorial(i - 1);
   }
   public static void main(String args[]) {
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter the number to which you need to find the factorial");
      int i = sc.nextInt();
      System.out.println("Factorial of the given number is ::"+ factorial(i));
   }
}

Output

Enter the number to which you need to find the factorial
12
Factorial of the given number is ::479001600

Samual Sam
Samual Sam

Learning faster. Every day.

Updated on: 30-Jul-2019

464 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements