bscodinglab

Recursion

Recursive :- Recursion in java is a process in which a method calls itself continuously. A method in java that calls itself is called recursive method. It makes the code compact but complex to understand.

A physical world example would be to place two parallel mirrors facing each other. Any object in between them would be reflected recursively.

Key points to keep in mind when working with recursion in Java:

    1. Define a base case: Every recursive function must have a base case to prevent infinite recursion. The base case provides a termination condition.
    2. Define a recursive case: The recursive case defines how the problem is broken down into smaller, similar subproblems. In each step, you should move closer to the base case.
    3. Maintain a stack: Each recursive call creates a new stack frame, so excessive recursion can lead to a stack overflow. Make sure your recursion is efficient and won’t lead to stack overflow errors for large input values.
    4. Test with care: Recursion can be powerful, but it can also be challenging to debug. Make sure to test and debug your recursive functions thoroughly.

Example :-

public class RecursionExample

{

    public static void main(String[] args)

            {

                        int result = factorial(5);

                        System.out.println(“Factorial of 5 is: ” + result);

            }

    public static int factorial(int n)

             {

                        // Base case: If n is 0 or 1, return 1.

                        if (n == 0 || n == 1)

                                    {

                                         return 1;

                                    }

                        else {

                                        // Recursive case: Call the factorial function with a smaller value.

                                        return n * factorial(n – 1);

                                  }

            }

}

Output :- Factorial of 5 is : 120

Advantages of Recursive Programming

The advantages of recursive programs are as follows:

  • Recursion provides a clean and simple way to write code.
  • Some problems are inherently recursive like tree traversals, For such problems, it is preferred to write recursive code.

Disadvantages of Recursive Programming

The disadvantages of recursive programs is as follows:

  • The recursive program has greater space requirements than the iterative program as all functions will remain in the stack until the base case is reached.
  • It also has greater time requirements because of function calls and returns overhead.

Note :- Both recursive and iterative programs have the same problem-solving powers, i.e., every recursive program can be written iteratively and vice versa is also true.