Recursion
What is recursion• Looping without a loop statement• A function that is part of its own  definition• Can only work if ther...
A recursive function• N Factorial• 1!   =   1  2!   =   1   x   2   =   2  3!   =   1   x   2   x   3 = 2! x 3 = 6  N!   =...
How recursion is handled• Every time a function is called, the  function values, local variables,  parameters and return a...
Dry-running a recursive callProcedure Printsequence(n)    n <- n-1    if n > 1 then       Printsequence(n)    endif    out...
Dry-running a recursive callProcedure Printsequence(n)    n <- n-1    if n > 1 then       output(n)       Printsequence(n)...
How to write a recursive         procedure• Code the general case  Result = n * Factorial(n-1)• Code the base case  Result...
Upcoming SlideShare
Loading in …5
×

Recursion

236 views

Published on

0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total views
236
On SlideShare
0
From Embeds
0
Number of Embeds
1
Actions
Shares
0
Downloads
5
Comments
0
Likes
0
Embeds 0
No embeds

No notes for slide

Recursion

  1. 1. Recursion
  2. 2. 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)
  3. 3. A recursive function• N Factorial• 1! = 1 2! = 1 x 2 = 2 3! = 1 x 2 x 3 = 2! x 3 = 6 N! = 1 x 2 x 3 x .... (N-2) x (N-1) x N = (N-1)! x N
  4. 4. 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!
  5. 5. Dry-running a recursive callProcedure Printsequence(n) n <- n-1 if n > 1 then Printsequence(n) endif output(n)EndProcedure
  6. 6. Dry-running a recursive callProcedure Printsequence(n) n <- n-1 if n > 1 then output(n) Printsequence(n) endifEndProcedure
  7. 7. How to write a recursive procedure• Code the general case Result = n * Factorial(n-1)• Code the base case Result = 1• Ensure that the base case is reached after a finite number of recursive calls

×