hopefully this lesson will give you an inception of what recursion is
Post on 01-Jan-2016
214 Views
Preview:
TRANSCRIPT
Base Case (also called Terminating Case)This is checked for at the beginning of the method
and is the case where you simply return from the method and do not make any more recursive calls
Recursive CallThis is the point in the method where the method
calls itself. It can be done more than once.Change
usually a or a increment/decrement, this is how the input variables change from one recursive call to the next.
Without a well thought out base case and change of the variables, it is very easy for recursion to turn into an infinite loop of the method continuously calling itself over and over.
When this happens, the program will crash due to memory restrictions since a method call will create duplicates of variables
int factorialLoop(int n){
int factorial = 1; //factorial to be returned
//goes through each number from n to 1
//multiplies each number in the sequence
for(int m = n; m >= 1; m--){
factorial *= m;
}
return factorial; //returns total
}
int factorialRecur(int n){if (n==1){
//terminating casereturn 1;
}else{//recursive callreturn n * factorialRecur(n-1);
}}
Remember for factorials that n! = n * (n-1)!
So we can design our function to call itself in the form f(n) = n * f(n-1)
But where do we stop? Remember that n! = 1*2*3*…*(n-2)*(n-1)*n
So as we progress from n to n-1, we must stop when we reach 1.
open()Returns doll inside
isAShell()Answers whether the doll is a shell
getSize()Returns the size of the doll
double getSmallestSize(NestingDoll doll){
Nesting_Doll doll_inside;
if( !doll.isAShell() ){ //terminating case return doll.Get_Size() ; }else{
//recursive call return getSmallestSize(doll.Open()); }}
2 Recursive call in a method will give it a Big O of 2n.Ex: 2 Recursive call with a tree depth of 5:
top related