Direct vs. Indirect Recursion
Explore the concepts of direct and indirect recursion in Java. Understand how recursive methods call themselves or each other, including base and recursive cases, to solve problems effectively. This lesson prepares you to apply these techniques in coding interviews and practical scenarios.
We'll cover the following...
Direct Recursion
Direct recursion occurs when a method calls itself.
This results in a one-step recursive call: the method makes a recursive call inside its own body.
The code snippet below gives an example of a direct recursive method that computes the square of a number.
We will now briefly discuss the two main parts of a recursive method, the base case and the recursive case, implemented in the code above.
The Base Case
We have defined the base case on line 5 where it states that when the variable n equals to , the method should terminate and start popping frames from the stack.
The Recursive Case
Let’s take a look at the mathematical operation required to perform . We need to decrement the value of n in such a way that we can use it to call the same method but not change the mathematical formula. We get this:
...