Recursion AP Computer Science A Mr. Langner By: Thomas Robbins
Recursion happens whenever a method has a statement inside it that causes the method to call itself. Example: Public int recursion(int a, int b) { //other body statements return 1 + recursion(int a, int b-1); } Overview
Two Important Things There are two things to know when coding with recursion; 1)If the problem is simple and easy, solve it right away. 2)If the problem isn’t so simple and appears very difficult, you need to break it down into smaller parts. Then solve these.
Example Say you want to divide a piece of wood into x amount of parts.
Example You will use recursion until all the pieces of wood are small enough. Remember the two important things: 1)If the wood is small enough, stop dividing 2)Else, divide the wood in two pieces and do the same for the next pieces.
Example Etc, etc, until the pieces are small enough
Coding Examples Now that we understand the principle behind recursion, we can take a look at some specific examples. Probably the easiest way to describe recursion to someone would be to relate factorials. Ex: 5! = 5 * 4 * 3 * 2 * 1 = 120 Ex: 3! = 3 * 2 * 1 = 6
Psuedocode 1. If the number is equal to one, then the factorial equals one. 2. Else, the factorial of the number equals itself times itself minus one. factorial(0) = 1, factorial(1) = 1 factorial(N) = N * factorial( N-1 )
Simple Code The Recursion that progresses towards the base case. Code similar to this is nearly mandatory on all recursive methods. It’s called a “Base case” and prevents the method from entering an infinite loop. static int fact(int n) { if (n <= 1) { return 1; return 1;} else { return n * fact(n-1); return n * fact(n-1);}
Break it down! Terrible pun aside, here’s a good break down of the factorial method’s process: factorial(5) = 5 * factorial(4) = 5 * ( 4 * factorial(3)) = 5 * ( 4 * factorial(3)) = 5 * ( 4 * (3 * factorial(2))) = 5 * ( 4 * (3 * factorial(2))) = 5 * ( 4 * (3 * (2 * factorial(1)))) = 5 * ( 4 * (3 * (2 * factorial(1)))) = 5 * ( 4 * (3 * (2 * (1 * factorial(0))))) = 5 * ( 4 * (3 * (2 * (1 * factorial(0))))) = 5 * ( 4 * (3 * (2 * (1 * 1)))) = 5 * ( 4 * (3 * (2 * (1 * 1)))) = 5 * 4 * 3 * 2 * 1 * 1 = 120 = 5 * 4 * 3 * 2 * 1 * 1 = 120
Another example of Recursion! Counting the number of bowling pins in a triangle: trianglePins(int N) //N is the number of rows { if ( N == 1 ) if ( N == 1 ) return 1; return 1; else else return N + Triangle( N-1 ); return N + Triangle( N-1 ); }
The breakdown trianglePins(5 ) = 5 + trianglePins (4) = 5 + (4 + trianglePins(3)) = 5 + (4 + trianglePins(3)) = 5 + (4 + (3 + trianglePins(2))) = 5 + (4 + (3 + trianglePins(2))) = 5 + (4 + (3 + (2 + trianglePins(1)))) = 5 + (4 + (3 + (2 + trianglePins(1)))) = 5 + (4 + (3 + (2 + 1))) = 5 + (4 + (3 + (2 + 1))) = 5 + (4 + (3 + 3)) = 5 + (4 + (3 + 3)) = 5 + (4 + 6) = 5 + (4 + 6) = = = 15 = 15