Ok, quick recursion review.
Look at my code below of an example of recursion. Review the comments to see if you understand how it works:
public class TestRead
{
public static void main(String[] args)
{
//Test Cases
System.out.println(recursiveMethod(1));
System.out.println(recursiveMethod(2));
System.out.println(recursiveMethod(3));
System.out.println(recursiveMethod(4));
System.out.println(recursiveMethod(5));
System.out.println(recursiveMethod(6));
System.out.println(recursiveMethod(7));
System.out.println(recursiveMethod(8));
System.out.println(recursiveMethod(9));
System.out.println(recursiveMethod(10));
}
/* Recursive Method
* Two important things regarding how we declare here:
* First is what we send this method
* Second is what this method returns
*
* Those two things will be important to remember while we implement our method
*/
public static int recursiveMethod(int n)
{
/* Base Case:
* For this method, our Base Case (or, end case) is when n==1.
* When this occurs, we want to return n (which will equal 1)
*/
if(n==1)
return n;
/* If this is not the Base Case, we want to do our next step. For this method,
* we want to multiply n with our call to recursiveMethod again. The very thing
* that makes a recursive method so it that it will call itself.
*/
else
/* Now, there are two important things here. The first is the fact that we
* are sending this method a variable that is different from the variable
* that this method is currently running with. If you send it the same variable,
* it will do the same thing, and just loop forever. The second important thing
* is our return call. This says we want to return the value of n mulitplied by
* our next call this method.
*
* Remember, this method will return an int, so when we call this method below,
* it will return an int which we can multiply by n. We will then return THAT
* value to wherever this method was called from. That could be at our main, or
* it could be at another instance of this method.
*/
return n*recursiveMethod(n-1);
}
}
This program results in the following cases and results:
Lets have a look at the first 3 cases and trace them.
CASE 1:
Call: recursiveMethod(1)
Hits Base Case, returns 1 to main
CASE 2:
Call: recursiveMethod(2)
Passes Base Case, calls recursiveMethod(1)
Hits Base Case, returns 1 to previous recursiveMethod call
Returns (2*1) to main
CASE3:
Call: recursiveMethod(3)
Passes Base Case, calls recursiveMethod(2)
Passes Base Case, calls recursiveMethod(1)
Hits Base Case, returns 1 to previous recursiveMethod call
Returns (2*1) to previous recursiveMethod call
Returns (3*2) to main
Do you see how the further we start from the base case, the more exponential our calls to our recursive method becomes? That is the essence of recursion. Do you understand this much?