Docsity

Recursion: Understanding Functions that Call Themselves, Slides of Computer Fundamentals

Toggle sidebar
bg1
.
5.13 Recursion
• Recursive functions
– Functions that call themselves
– Can only solve a base case
– Divide a problem up into
• What it can do
• What it cannot do
– What it cannot do resembles original problem
– The function launches a new copy of itself (recursion step)
to solve what it cannot do
– Eventually base case gets solved
• Gets plugged in, works its way up and solves whole problem
docsity.com
pf3
pf4
pf5
pf8
pf9
pfa
pfd

Partial preview of the text

Download Recursion: Understanding Functions that Call Themselves and more Slides Computer Fundamentals in PDF only on Docsity!

5.13 Recursion

• Recursive functions

– Functions that call themselves

– Can only solve a base case

– Divide a problem up into

• What it can do

• What it cannot do

– What it cannot do resembles original problem

– The function launches a new copy of itself (recursion step)

to solve what it cannot do

– Eventually base case gets solved

• Gets plugged in, works its way up and solves whole problem

5.13 Recursion

• Example: factorials

– Notice that

– Can compute factorials recursively

– Solve base case (1! = 0! = 1 ) then plug in

Outline

fig05_14.c (Part 1

of 2)

Outline

 - fig05_14.c (Part 
  • 1! = of 2)
  • 2! =
  • 3! =
  • 4! =
  • 5! =
  • 6! =
  • 7! =
  • 8! =
  • 9! =
  • 10! =

5.14 Example Using Recursion: The

Fibonacci Series

• Set of recursive calls to function fibonacci

f( 3 )

f( 2 ) f( 1 )

f( 1 ) f( 0 ) return 1

return 1 return 0

return +

return +

Outline

fig05_15.c (Part 1

of 2)

Outline

Program Output

(continued)

Enter an integer: 5 Fibonacci( 5 ) = 5

Enter an integer: 6 Fibonacci( 6 ) = 8

Enter an integer: 10

Fibonacci( 10 ) = 55

Enter an integer: 20 Fibonacci( 20 ) = 6765

Enter an integer: 30 Fibonacci( 30 ) = 832040

Enter an integer: 35 Fibonacci( 35 ) = 9227465

5.14 Example Using Recursion: The

Fibonacci Series

5.15 Recursion vs. Iteration