Java Program to Find Factorial Using Recursion
Recursion is a powerful programming concept where a function calls itself to solve a problem. Factorial is one of the most common examples used to understand recursion in Java.
In this tutorial, we will create a Java program to calculate the factorial of a number using recursion.
By the end of this guide, you will understand how recursive functions work in Java.
Concept Overview
The factorial of a number n is defined as n × (n-1) × (n-2) × ... × 1.
In recursion, we define the problem in terms of a smaller version of itself.
Base case: factorial of 0 or 1 is 1.
Program
import java.util.Scanner;
public class FactorialRecursion {
static long factorial(int n) {
if (n == 0 || n == 1)
return 1;
else
return n * factorial(n - 1);
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a number: ");
int num = sc.nextInt();
long result = factorial(num);
System.out.println("Factorial of " + num + " is: " + result);
}
}
Output
Enter a number: 5
Factorial of 5 is: 120
Detailed Explanation
The program defines a recursive function factorial() that calls itself with a smaller value each time.
The base condition ensures that the recursion stops when n becomes 0 or 1.
Each recursive call multiplies the current number with the result of factorial(n-1).
The main() method takes user input and calls the recursive function.
Example Walkthrough
Let us consider n = 5.
The recursion expands as: 5 × 4 × 3 × 2 × 1 = 120.
Applications
Recursion is widely used in tree traversal, searching algorithms, dynamic programming, and mathematical computations.
Advantages of This Approach
This program helps beginners understand recursion clearly.
It simplifies problems by breaking them into smaller subproblems.
Limitations
Recursion can lead to stack overflow for large inputs.
Improvements You Can Make
You can add memoization to optimize repeated calls.
You can also compare recursive and iterative approaches.
This Java program builds a strong understanding of recursion and problem decomposition, which are essential in advanced programming.
Codecrown