...

/

Direct vs. Indirect Recursion

Direct vs. Indirect Recursion

This lesson explains two different types of recursion: direct and indirect recursion.

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.

Press + to interact
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.

Press + to interact
class Square {
// Recursive method to calculate square of a number
private static int square(int n) {
// Base case
if (n == 0) {
return 0;
}
// Recursive case
else {
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 00, 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 n2n^2. 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:

(n1)2 ...