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

Java Programming Java8Java Technologies

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
raja
Published on 25-Apr-2018 17:30:01
Advertisements