Title: Recursion
1Recursion
2What is recursion?
- a function calls itself
- direct recursion
- a function calls its invoker
- indirect recursion
f1
f
f2
3Outline of a Recursive Function
function header if (answer is known)
return the answer else recursive
call to solve a "smaller" problem
base case
recursive case
4Factorial (n) - recursive
5How Recursion Works
- a recursive function call is like any other
function call - each function call has its own activation record
(space for storing parameters and local
variables) - created when the function is called
- destroyed when the function returns to its caller
- activation records are stacked up as recursive
calls are made - when the base case is reached the recursion
unwinds
6Recursive Call Tree
RecFact (4)
long factorial (int n) if (n 0)
return 1 else return n factorial
(n-1)
What happens with factorial (-2)?
7Factorial (n) - iterative
Factorial (n) n (n-1) (n-2) ... 1
for n gt 0 Factorial (0) 1
8Euclid'sAlgorithm
- Finds the greatest common divisor of two
nonnegative integers that are not both 0 - Recursive definition of gcd algorithm
- gcd (a, b) a (if b is 0)
- gcd (a, b) gcd (b, a b) (if b ! 0)
- Write a recursive gcd function
- prototype?
- implementation?
9Tracing gcd (54, 30)
int gcd (int a, int b) if (b 0)
return a else return gcd (b, a
b)
10Iterative gcd?
11Another recursive definition
Fibonacci numbers are the sequence of integers
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, .
12Tracing fib(5)