Recursion is the process of having a method call itself on a continually refining set of data. As the data set is being refined, the same process is repeated over it (the data set). This works in a similar fashion as the loop body. There are three parts to a recursive solution: the Base Case, the Recursive Case, and the Recusive Step.
If the recursive process will return information, we need to ensure a connection exists across all the recursive calls for actually performing the return. This can be completed in two ways. First, return statements are listed in multiple locations, placed at exactly the point where the return is desired. This implementation will involve returning a specific or literal value within the base case and a subsequent recursive call within the recursive step. Second, a single return of a variable whose value is continually upated can be made at the end of the method. In this solution, the return variable will be assigned a specific or literal value within the base case and the result of a subsequent recursive call within the recursive step.
When creating a recursive solution, there are two points when actions can be taken. First, actions can be taken before making the recursive call and as we move into the recursion. Second, steps can also be taken as we return from recursive calls and as we move out of the recursion.
The main method should never be accessed in a recursive fashion. The JVM (c:\>java classname) will handle starting up a program by calling the main method.
During COP 3502 & 3503 (when I am teaching these courses):
public static int factorial(int n) {
if (n == 0 || n == 1) {
return 1;
}
else if (n > 1) {
return n * factorial(n - 1);
}
return 0;
}
public static int Fibonacci(int n) {
if (n == 0 || n == 1) {
return n;
}
else {
return Fibonacci(n - 1) + Fibonacci(n - 2);
}
}
public static int recursiveMethod1(int a[]) {
return recursiveMethod1(a, 1, a[0]);
}
public static int recursiveMethod1(int a[], int index, int data) {
if (index < a.length) {
if (data < a[index]) {
data = a[index];
}
data = recursiveMethod1(a, (index + 1), data);
}
return data;
}
public static int recursiveMethod2(int n) {
int result;
if(n <= 1) {
result = 0;
}
else if((n % 2) == 0) {
result = n * n + recursiveMethod2(n - 1);
}
else {
result = recursiveMethod2(n - 1);
}
return result;
}
Here are other recursive solutions, some of which include an iterative implementation for your reference.