1. Introduction
In this post, we will explore a Java program that calculates the factorial of a number using recursion. The factorial of a non-negative integer n is the product of all positive integers less than or equal to n. It is denoted by n!. For example, 5! = 5 × 4 × 3 × 2 × 1 = 120. The factorial function can be defined recursively as n! = n × (n – 1)! for n > 0 and 0! = 1.
2. Program Steps
1. Define the main class named FactorialCalculator.
2. Inside the main class, define the main method.
3. Inside the main method, define a variable num and assign the value for which we want to calculate the factorial.
4. Call the recursive factorial method, passing the num as a parameter.
5. Print the result.
3. Code Program
public class FactorialCalculator { // 1. Defining the main class
// Defining the recursive method to calculate factorial
static int factorial(int n) {
if (n == 0 || n == 1) // Base case: 0! and 1! are 1
return 1;
else
return n * factorial(n - 1); // Recursive call
}
public static void main(String[] args) { // 2. Defining the main method
int num = 5; // 3. Assigning the number for which we want to calculate factorial
int result = factorial(num); // 4. Calling the factorial method
// 5. Printing the result
System.out.println("Factorial of " + num + " is " + result);
}
}
Output:
Factorial of 5 is 120
4. Step By Step Explanation
– Step 1: The main class FactorialCalculator is defined.
– Step 2: The main method is defined inside the main class. This is the entry point of the Java program.
– Step 3: Inside the main method, a variable num is defined and assigned the value 5, for which we want to calculate the factorial.
– Step 4: The factorial method is called with num as a parameter. This method calculates the factorial of a number using recursion. If the number is 0 or 1, the factorial is 1. For any other number n, the factorial is calculated as n * factorial(n – 1).
– Step 5: The program prints the calculated factorial of the number 5, which is 120, to the console.