Title: Recursion
1Recursion
For example in the series
we use the operator ! factorial.
2In the algorithm for the series we have used
Along this line
So factorial(5) calls factorial(4),
factorial(4) calls factorial(3),
factorial(3) calls factorial(2), etc.
3(No Transcript)
4(No Transcript)
5Fibonacci
1, 1, 2, 3, 5, 8, 13, 21, ...
6Applying recursion
fibonacci(n)
This algorithm expresses clearly that a term
equals the sum of the two preceding terms.
7(No Transcript)
8Bisection
No tests for roots on the specified interval!
9- Layout of a recursive function
- no recursive calls needed (stopping case), see
factorial(1) - one or more cases where a recursive call is
needed
Make sure the function stops!
- Advantage formulation is simple and clear
- Disadvantage inefficient
- calling a function takes time a.o. transport of
arguments - more calls are needed, see fibonacci
10Towers of Hanoi
Bring disks from pole A to pole C.
A
B
C
11- n1 A to C
- n 2 A to B. A to C. B to C
- n 3 Use step n 2 to move the first two disks
to B while - using C as temporary storage.
- A to B. Use step n 2 to move these
two disks - from B to C using A as temporary
storage -
-
- n-2 ..
- n-1 Use step n-2 to move n-2 disks from A to B
(C temporary). - Move A to C.
- Use step n-2 to move the n-2 disks from
B to C (A temporary) - n Use step n-1 to move n-1 disks from A to B
(C temporary) - Move A to C.
- Use step n-1 to move the n-1 disks from
B to C (A temporary)
Demo
12- n1 Move A to C
- Use step n-1 to move n-1 disks from A to B (C
temporary) - Move A to C
- Use step n-1 to move the n-1 disks from
B to C (A temporary)
13- Sometimes a variable with the values
- 0 (false or not true) or
- 1 (true)
- Assume you want adult to become 1 if age 18
- adult to become 0
if age lt 18 - adult is a so-called boolean variable
- You can accomplish that in two ways
Or