Sitemap

Recursion

4 min readApr 22, 2024

--

The process of having a function call itself is known as recursion. This method offers a way to deconstruct complex issues into simpler, more manageable issues. Recursion has main three key points that always have to be achieved. (For elucidation within this article, Java programming language is employed for explanation purposes.)

  1. Caller
  2. Recursive calls
  3. Stop condition
Press enter or click to view image in full size

I above image gives the basic idea with example regarding the java recursion.

Now let us look at one or more examples of how can implement recursion using the Factorial Function.

Example :

Factorial Function:

The factorial of a non-negative integer 𝑛n, denoted by 𝑛!n!, is the product of all positive integers less than or equal to 𝑛n.

Example:

For example, 5!=5×4×3×2×1=1205!=5×4×3×2×1=120.

Java Code:

public class FactorialExample {

// Recursive function to calculate factorial
public static int factorial(int n) {
// Base case: factorial of 0 or 1 is 1
if (n == 0 || n == 1) {
return 1;
} else {
// Recursive case: factorial of n is n * factorial(n-1)
return n * factorial(n - 1);
}
}

public static void main(String[] args) {
int number = 5;
int result = factorial(number);
System.out.println("Factorial of " + number + " is: " + result);
}
}

Explanation:

  • In the factorial method, we define our recursive function.
  • We start with a base case: if 𝑛n is 0 or 1, the factorial is 1. This is the stopping condition for our recursion.
  • If 𝑛n is greater than 1, we recursively call factorial(n - 1). This means we calculate the factorial of 𝑛−1n−1 and multiply it by 𝑛n.
  • This process continues until we reach the base case.
  • In the main method, we simply call factorial with a number (here, 5) and print the result.

Recursion vs Iteration

Recursion

Definition

  • Function calls itself to solve a problem.

When to Use

When the problem can be broken down into smaller, similar subproblems.

Get Viraj Ridiyagama’s stories in your inbox

Join Medium for free to get updates from this writer.

Advantages

  • Simplifies complex problems into smaller, more manageable parts.
  • Elegant and intuitive for certain problems like tree traversal or factorial calculation.

Disadvantages

  • Can be less efficient in terms of memory usage due to function call overhead and stack space.
  • Harder to debug and understand for some programmers.

Iteration

Definition

  • Using loops to repeat a set of instructions until a condition is met.

When to Use

  • When the problem can be solved by repeating a set of instructions without dividing it into smaller parts.

Advantages

  • Often more efficient in terms of memory and performance compared to recursion.
  • Easier to understand and debug for many programmers.

Disadvantages

  • Can be more complex for certain problems that naturally lend themselves to recursion.
  • May require more code and be less elegant for some algorithms.

How can we identify what problem we can solve using recursion?

Problem Decomposition: If the problem can be decomposed into smaller instances of the same problem (e.g., traversing subdirectories in a directory tree), recursion is a natural choice.

  • Natural Hierarchical Structure: Problems with a hierarchical or nested structure often lend themselves well to recursion (e.g., tree traversal, nested data structures).
  • Divide and Conquer: If the problem can be solved by breaking it down into smaller, similar subproblems, recursion is often an effective approach.

When dealing with problems that exhibit hierarchical structure or can be broken down into smaller instances of the same problem, recursion can provide a clean and elegant solution. In the case of directory tree traversal, recursion simplifies the process of traversing nested directories and performing operations on files.

Pros of Recursion:

Simplicity and Readability:

  • Recursion can lead to simpler and more elegant solutions for certain problems, making the code easier to understand.
  • It often reflects the natural structure of the problem, making the code intuitive for developers.

Divide and Conquer:

  • Recursion allows problems to be broken down into smaller, more manageable subproblems.
  • This can simplify complex problems by reducing them to simpler instances of the same problem.

Ease of Implementation:

  • For problems that are inherently recursive, implementing them recursively can be more straightforward than using iterative approaches.

Cons of Recursion:

  1. Performance Overhead:
  • Recursive function calls incur overhead in terms of memory usage and performance.
  • Each recursive call requires additional stack space, and excessive recursion can lead to stack overflow errors.

Potential for Infinite Recursion:

  • If not implemented correctly, recursion can lead to infinite loops, causing the program to hang or crash.
  • Careful consideration of base cases is necessary to prevent this.

Debugging Complexity:

  • Debugging recursive functions can be challenging, especially for larger and more complex codebases.
  • Tracing the flow of execution through multiple recursive calls can be difficult, leading to longer debugging cycles.

Stack Overflow Risk:

  • Recursion may lead to stack overflow errors if the depth of recursion exceeds the stack size limit.
  • This risk is particularly pronounced in languages like Java that have limited stack space.

--

--

Viraj Ridiyagama
Viraj Ridiyagama

Written by Viraj Ridiyagama

Software Engineer - Full Stack | React.js & Node.js Developer | Java | SQL | Tech Enthusiast | Blogger | Research Enthusiast |