20
Hopefully this lesson will give you an inception of what recursion is.

Hopefully this lesson will give you an inception of what recursion is

Embed Size (px)

Citation preview

Hopefully this lesson will give you an inception of what recursion is.

a method of computer programming in which a function can call itself*

*source - Wikipedia

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.

factorialRecur(4)

4 * = 24

factorialRecur(3)

3 * =6

factorialRecur(2)

2 * = 2

factorialRecur(1)

1

A set of dolls of decreasing sizes placed one inside another.

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()); }}

1 Recursive call in a method will give it a Big O of n.Ex: 1 Recursive call with a tree depth of 5:

2 Recursive call in a method will give it a Big O of 2n.Ex: 2 Recursive call with a tree depth of 5:

Some algorithms are recursive in nature so they are easier to program

Some algorithms are more efficiently done recursively

Some algorithms can only be programed recursively

But a lot of the recursive methods you will start out programing are none these three but are easier to program