Presentation is loading. Please wait.

Presentation is loading. Please wait.

Fall 2008ACS-1805 Ron McFadyen1 Ch 8 Recursion Recursion occurs when a method (or function) calls itself.

Similar presentations


Presentation on theme: "Fall 2008ACS-1805 Ron McFadyen1 Ch 8 Recursion Recursion occurs when a method (or function) calls itself."— Presentation transcript:

1 Fall 2008ACS-1805 Ron McFadyen1 Ch 8 Recursion Recursion occurs when a method (or function) calls itself

2 Fall 2008ACS-1805 Ron McFadyen2 Factorials n! = n (n - 1)! 3!=3*2! 4!=4*3! 2!=2*1! Base cases: 0! = 1 1! = 1

3 Fall 2008ACS-1805 Ron McFadyen3 N! n! parameter n, an integer If n=0 return 1 Else if n=1 return 1 Else return n * (n-1)! Recursive call

4 Fall 2008ACS-1805 Ron McFadyen4 N! Number penguin.n! ( [123] n) No variables If ( n == 0 ) Return 1 Else If ( n == 1 ) Return 1 Else Do Nothing Return ( ( n * ( penguin.n! ( ( n - 1 ) ) ) ) ) Call n! again with the argument n-1 After (n-1)! is computed, return the value n * (n-1)!

5 Fall 2008ACS-1805 Ron McFadyen5 The call stack A stack in computer science is an area of memory where information can be placed, used, and then removed Operations: push, pop, get Information is pushed onto the stack Information is popped off the stack The top entry is accessible … lifo: last in, first out pushA new entry goes onto the stack… the stack becomes larger with the new entry on top

6 Fall 2008ACS-1805 Ron McFadyen6 The call stack Our sample program begins executing my first method First of all, Information for my first method is pushed onto the stack x=4 xFactorial=1 Current instruction is … Then, Information for penguin.n! is pushed onto the stack n=4 Current instruction is … Then…


Download ppt "Fall 2008ACS-1805 Ron McFadyen1 Ch 8 Recursion Recursion occurs when a method (or function) calls itself."

Similar presentations


Ads by Google