Recursion - PowerPoint PPT Presentation

1 / 13
About This Presentation
Title:

Recursion

Description:

Recursion. For example in the series. we use the operator ! = factorial. ... fibo(5) fibo(4) fibo(3) fibo(2) fibo(1) fibo(3) fibo(2) fibo(2) fibo(1) Bisection ... – PowerPoint PPT presentation

Number of Views:91
Avg rating:3.0/5.0
Slides: 14
Provided by: Infor374
Category:
Tags: fibo | recursion

less

Transcript and Presenter's Notes

Title: Recursion


1
Recursion
For example in the series
we use the operator ! factorial.
2
In 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)
5
Fibonacci
1, 1, 2, 3, 5, 8, 13, 21, ...
6
Applying recursion
fibonacci(n)
This algorithm expresses clearly that a term
equals the sum of the two preceding terms.
7
(No Transcript)
8
Bisection
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

10
Towers 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
Write a Comment
User Comments (0)
About PowerShow.com