• November 20, 2024

How to implement Recursion in Java?

Recursion is a technique in programming where a function calls itself in order to repeat a set of instructions until a certain condition is met. Instead of using loops to iterate through data, recursion relies on a function calling itself repeatedly to solve a problem. Recursion is often used for problems that can be broken down into smaller subproblems, with each subproblem being solved recursively until the entire problem is solved.

Here is an example code in Java that demonstrates the concept of recursion:

public class RecursionExample {
public static void main(String[] args) {
int n = 5;
int result = factorial(n);
System.out.println(“Factorial of ” + n + ” is ” + result);
}

public static int factorial(int n) {
    if (n == 0) {
        return 1;
    } else {
        return n * factorial(n - 1);
    }
}

}

In this example, we define a method called factorial that takes an integer argument n and returns the factorial of n. The factorial method calls itself recursively until it reaches the base case, which is when n is equal to 0. When n is 0, the method returns 1. Otherwise, the method multiplies n with the result of calling itself with n – 1 as the argument. This continues until the base case is reached, at which point the final result is returned.

When we run this program with an input of 5, the output will be:

Factorial of 5 is 120

This is because 5! (the factorial of 5) is equal to 5 * 4 * 3 * 2 * 1, which is equal to 120. The factorial method is able to compute this value recursively by breaking it down into smaller subproblems until it reaches the base case.

Leave a Reply

Your email address will not be published. Required fields are marked *