Direct vs. Indirect Recursion
This lesson explains two different types of recursion: direct and indirect recursion.
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.
class ExampleClass {private static void f() {// some code...f();//some code...}public static void main(String args[] ) {// Method called here}}
The code snippet below gives an example of a direct recursive method that computes the square of a number.
class Square {// Recursive method to calculate square of a numberprivate static int square(int n) {// Base caseif (n == 0) {return 0;}// Recursive caseelse {return square(n-1) + (2 * n) - 1;}}public static void main( String args[] ) {int input = 6;int output = square(input);System.out.println("The square of the number " + input + " is: " + output);}}
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:
...