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.
Some helps when creating recursive solutions are:
The function main should never be accessed in a recursive fashion.
During any course I am teaching:
int factorial( int n ) {
if ( n == 0 || n == 1 ) {
return 1;
}
else if ( n > 1 ) {
return n * factorial( n - 1 );
}
return 0;
}
int Fibonacci(int n) {
if ( n == 0 || n == 1 ) {
return n;
}
else {
return Fibonacci( n - 1 ) + Fibonacci( n - 2 );
}
}
int recursiveFunction1( int a[], int N ) {
return recursiveFunction1Helper(a, N, 1, 0);
}
int recursiveFunction1Helper( int a[], int N, int index, int data ) {
if ( index < N ) {
if ( a[data] < a[index] ) {
data = index;
}
data = recursiveFunction1Helper( a, N, ( index + 1 ), data );
}
return data;
}
int recursiveFunction2( int n ) {
int result;
if( n <= 1 ) {
result = 0;
}
else if( ( n % 2 ) == 0 ) {
result = n * n + recursiveFunction2( n - 1 );
}
else {
result = recursiveFunction2( n - 1 );
}
return result;
}