Recursion
AP Computer Science A
Chris Vollmer
Recursion
Recursive Definitions
24, 88, 40, 37
A LIST is a: number
or a: number comma LIST
Recursive Definitions
number comma LIST
24 , 88, 40, 37
number comma LIST
88 , 40, 37
number comma LIST
40 , 37
number
37
Recursive Syntax
Recursive Definition
public int sum(int sum)
{
int result;
if(num==1)
result=1;
else
result=num+sum(num-1);
return result;
}
Base Case or terminating condition
Move toward base case
Recursive Definition
1! = 1
N! = N * (N-1)!
Recursive Definition
public static int factorial(int n)
{
if (n==0)
return 1;
else
return n*factorial(n-1)
}
Handout3: Recursion
Tracing Recursive Method
Step 1
[3] return 1 * factorial(0)
[2] return 2 * factorial(1)
[1]return 3* factorial(2)
public static int factorial(int n)
{
if (n==0)
return 1;
else
return n*factorial(n-1)
}
factorial(3)
Step 2
[1] 1 * factorial(0)== 1
[2] 2 * factorial(1) 1 == 2
[3] 3* factorial(2) 2 == 6
Recursive Definition Solution (factorial)
5!
5 * 4!
4 * 3!
3 * 2!
2 * 1!
1
2
6
24
120
Recursive Programming
public int sum (int num)
{
int result;
if (num == 1)
result = 1;
else
result = num + sum (num - 1);
return result;
}
Method call: sum(3) - try solving
Answer on next slide
Recursive Programming Solution
main
sum
sum
sum
sum(3)
sum(1)
sum(2)
result = 1
result = 3
result = 6 final answer
result = num + sum (num - 1)
Down the stack.. calls sum(num-1)
Up the stack... replace method call with result and add to num for new result.
Example - Sum(3)
Video Tutorial
Practice - Handout 3: Tracing Recursion
1. public static int factorial(int n){
if(n==0)
return 1;
else
return n* factorial(n-1)
}
Factorial (5)
Work Down Stack...
f(5) ---- 5 * f(4)
f(4) ---- 4* f(3)
f(3) ---- 3 * f(2)
f(2) ---- 2 * f(1)
f(1) ---- 1 * f(0)
f(0) --- returns 1
n==0 terminates
Once loop terminates replace method call with result and work back up stack
f(5) ---- 5 * f(4) = 5 * 24
f(4) ---- 4* f(3) = 4 * 6
f(3) ---- 3 * f(2) = 3 * 2
f(2) ---- 2 * f(1) = 2 * 1
f(1) ---- 1 * f(0) = 1 * 1
f(0) --- returns 1
Final Answer = 120
You Do: Complete the rest of Handout 3: Tracing Recursion
We do: Example/Solution for #1
Recursion vs. Iteration
Indirect Recursion
16
Indirect Recursion
17
m1
m2
m3
m1
m2
m3
m1
m2
m3
Maze Traversal
18
Maze Traversal
19
Towers of Hanoi
20
Towers of Hanoi
See solution - http://towersofhanoi.info/Animate.aspx
Towers of Hanoi - Algorithm
22
Towers of Hanoi
23
Recursion in Sorting
... The rest of that story a little later...
24