Factorial Java Program using Recursion [ 2024 ]
Factorial Java Program using Recursion
Write a Java program to compute the factorial of a 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

Java Tutorials
Java Tutorial on this website:
For more information on Java, visit the official website :