Learn how to calculate the factorial of a number using recursion in Java. This step-by-step guide explains recursion in simple words with code examples for beginners.
Article Body
Recursive Method to Find Factorial in Java with Easy Explanation
π Introduction
In programming, factorial is a common mathematical function used to solve many problems like permutations, combinations, and recursion practice. In this article, we will learn how to calculate the factorial of a number using recursion in java.
Weβll go step by step and explain everything in simple terms. Whether you're a beginner or just brushing up your Java skills, this article will help you understand recursion easily.
π What is a Factorial?
The factorial of a number n is written as n! and is the product of all positive integers from 1 to n.
Here is the full Java code with step-by-step explanation below.
public class FactorialUsingRecursion {
// Recursive method to calculate factorial
public static int factorial(int n) {
if (n == 0 || n == 1) {
return 1; // Base case: factorial of 0 or 1 is 1
} else {
return n * factorial(n - 1); // Recursive call
}
}
public static void main(String[] args) {
int number = 5; // You can change this number to test
int result = factorial(number);
System.out.println("Factorial of " + number + " is: " + result);
}
}
π Step-by-Step Explanation
1. Function Definition
public static int factorial(int n)
We define a method named factorial that takes an integer n.
It returns an int value which is the factorial of n.
2. Base Case
if (n == 0 || n == 1) {
return 1;
}
This is very important in recursion.
It stops the recursion from going forever.
It tells the function: If n is 0 or 1, return 1.
3. Recursive Call
return n * factorial(n - 1);
This is the heart of recursion.
The function calls itself with a smaller number (n-1) and multiplies it with n.
4. Main Method
int number = 5;
int result = factorial(number);
System.out.println("Factorial of " + number + " is: " + result);
We call the recursive function with the number 5.
It returns 120, which is stored in result and printed.
π§ Dry Run (How It Works Internally)
Letβs see what happens when we calculate factorial(4):
Rahul is a software engineer and editor at Galaxy Founder, passionate about technology, startups, and digital innovation. With a keen eye for emerging trends and a love for clean, efficient code, Rahul shares insights and resources to help others navigate the evolving tech landscape.
Comments