Direct vs. Indirect Recursion
This lesson explains two different types of recursion: direct and indirect recursion.
We'll cover the following...
Direct Recursion
If a function calls itself, it’s known as direct recursion. This results in a one-step recursive call: the function makes a recursive call inside its own function body.
Below is an example of a direct recursive function that computes the square of a number:
Indirect Recursion
If the function f1 calls another function f2 and f2 calls f1 then it is indirect recursion (or mutual recursion). This is a two-step recursive call: the function calls another function to make a recursive call.
Note: For indirect recursion, both the functions need to be declared before they are defined.
What is an example of indirect recursion?
Below is an implementation of indirect recursion that prints the first 20 integers:
Conclusion
In conclusion, we learned that direct recursion happens when a function invokes itself directly within its body, creating a loop of self-calls that can be resolved through a base case. This straightforward recursion method is useful for problems that can be broken down into similar subproblems. Alternatively, indirect recursion involves at least two functions working together. In this scenario, one function calls a second function, which then calls the original function back, creating a recursive loop between them. This type of recursion can be advantageous for more complex scenarios where a single function alone cannot effectively solve the problem.