recursion

7
Recursion

Upload: grahamwell

Post on 22-Nov-2014

342 views

Category:

Documents


0 download

DESCRIPTION

 

TRANSCRIPT

Page 1: Recursion

Recursion

Page 2: Recursion

What is recursion

• Looping without a loop statement

• A function that is part of its own definition

• Can only work if there’s a terminating condition, otherwise it goes forever (the base case)

Page 3: Recursion

A recursive function

• N Factorial• 1! = 11! = 1

2! = 1 x 2 = 22! = 1 x 2 = 23! = 1 x 2 x 3 = 2! x 3 = 63! = 1 x 2 x 3 = 2! x 3 = 6N! = 1 x 2 x 3 x .... (N-2) x (N-1) x N = (N-1)! x N N! = 1 x 2 x 3 x .... (N-2) x (N-1) x N = (N-1)! x N

Page 4: Recursion

How recursion is handled

• Every time a function is called, the function values, local variables, parameters and return addresses are pushed onto the stack.

• Over and Over again• You might run out!

Page 5: Recursion

Dry-running a recursive call

Procedure Printsequence(n)

n <- n-1

if n > 1 then

Printsequence(n)

endif

output(n)

EndProcedure

Page 6: Recursion

Dry-running a recursive call

Procedure Printsequence(n)

n <- n-1

if n > 1 then

output(n)

Printsequence(n)

endif

EndProcedure

Page 7: Recursion

How to write a recursive procedure

• Code the general caseResult = n * Factorial(n-1)

• Code the base caseResult = 1

• Ensure that the base case is reached after a finite number of recursive calls