Search⌘ K
AI Features

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.

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.

Java
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 ...

Java
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 ...