Site icon TestingDocs.com

Factorial Java Program using Recursion

Program Description

Write a java program to compute factorial of given number n using Recursion.

IPO Chart

Input

We will take input from the user for n

Process 

For n>= 0 , we will do a recursive call using the below formula

fact(n) = n* fact(n-1)

Output

factorial of n.

 

 

 

Java Program

package recursion;

import java.util.Scanner;

/**************************************************
 * FactorialRecursion.java
 * @program   	: Factorial Using Recursion
 * @web        	: www.TestingDocs.com
 * @author      :  
 * @version     : 
 **************************************************/
public class FactorialRecursion {
  //Main method
  public static void main(String[] args) {
    int n;
    Scanner input = new Scanner(System.in);
    System.out.println("Enter positive n:= ");
    n = input.nextInt();

    if(n >= 0)
      System.out.println("Factorial of  " + n + " is = " + factRecurFun(n));
    else
      System.out.println("Enter valid input.");
  }

  /**************************************************
   * factRecurFun() is a recursive method to compute
   * factorial of the given number.
   **************************************************/
  public static int factRecurFun(int n) {
    // base case
    if(n < 1 )   
      return 1;
    else
      //Recursive call
      return n*factRecurFun(n-1);
  }
}

 

Program Output

Enter positive n:=
6
Factorial of 6 is = 720

Screenshot

Exit mobile version