Factorial Program in Java Using Recursion. In the world of computer programming recursion is an important and interesting concept where function call themselve to solve problem. An example of recursion in action can be calculating factorial of a number. In this article we will write a factorial program in java using recursion.
Table of Contents
Concept of Recursion
Recursion is a process where a method calls itself to solve a problem. A recursive method solves a problem by solving smaller instances of the same problem, except for the simplest case, known as the best case, which it solve directly. In the case of calculating factorials, recursion fix naturally because a factorial of a number can be expressed in the terms of the factorial of a smaller number.
Factorial Program in Java Using Recursion
import java.util.Scanner;
class factorial {
public static long factorial(int n){
//base case
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.println("Enter the number ");
int n = sc.nextInt();
if(n<0){
System.out.println("Invalid input");
}
else{
System.out.println("Factorial of " + n + " = " + factorial(n));
}
}
}
Output
In the above Java program-
- The
factorial
method checked if n is 0 or 1. If true it returns 1, as the factorial of 0 and 1 is 1. This is the base condition that prevents the method from calling itself indefinitely. - If n is greater than 1 the method calls itself with n-1. this step breaks down the problem into smaller instances until it reaches the base case(n=0 or 1).
Recursion offers a powerful and elegant approach to solving problems that can be broken down into smaller instances of the same problem.
Happy Coding & Learning
2 thoughts on “Factorial Program in Java Using Recursion”