Presentation is loading. Please wait.

Presentation is loading. Please wait.

Recursion Gordon College CPS212

Similar presentations


Presentation on theme: "Recursion Gordon College CPS212"— Presentation transcript:

1 Recursion Gordon College CPS212
Adapted from Nyhoff: ADTs, Data Structures, and Problem Solving

2 Recursive Functions Recursive programming is based off of Recursive Formulas Definition of Recursive Formula a formula that is used to determine the next term of a sequence using one or more of the preceding terms. Example of Recursive Formula The recursive formula for the sequence 5, 20, 80, 320, ... is an = 4 an-1 How would you program such a thing?

3 Program Solution int series(int n) { } if (n == 1) return 5;
return 4 * series(n-1); } Base case Recursive case

4 Recursion A function is defined recursively if it has the following two parts: An anchor or base case The function is defined for one or more specific values of the parameter(s) An inductive or recursive case The function's value for current parameter(s) is defined in terms of previously defined function values and/or parameter(s) How would you normally write a powers – OK let’s say you can’t use the powers operator…use a loop with so that it can be variable!!

5 Recursive Example Consider a recursive power function double power (double x, unsigned n) { if ( n == 0 ) return 1.0; else return x * power (x, n-1); } Which is the anchor? Which is the inductive or recursive part? How does the anchor keep it from going forever? No loops used here: simply call: x = power(3.0,3);

6 Recursive Example Note the results of a call Recursive calls
Resolution of the calls Let’s check out the run-time stack for this example

7 Recursive Factorial another example
n! = 1 x 2 x …x n, for n > 0 n! = (n – 1)! X n 5! = 5 x 4! 120 4! = 4 x 3! 24 3! = 3 x 2! 6 2! = 2 x 1! 2 1! = This is born to be used for recursion…see if you can construct the function to perform this recursively?? How would this be written conventionally?? int fact(int n) { if (n==1) return 1; return n * fact(n – 1); }

8 Another Example of Recursion
Fibonacci numbers 1, 1, 2, 3, 5, 8, 13, 21, 34 f1 = 1, f2 = 1 … fn = fn -2 + fn -1 A recursive function double Fib (unsigned n) { if (n <= 2) return 1; else return Fib (n – 1) + Fib (n – 2); } Add the previous two in the series to get the next. A loop does nicely in this case

9 A Bad Use of Recursion Why is this inefficient?
Note the recursion tree Remember each function call is overhead… This is can be done in a much more efficient manner using a normal algorithm – with a loop.

10 Uses of Recursion Binary Search See source code
Note results of recursive call Recursive functions need not return values via a return statement – but may instead return values via the parameters or may return no values.

11 Uses of Recursion Palindrome checker
A palindrome has same value with characters reversed racecar Recursive algorithm for an integer palindrome checker If numDigits <= 1 return true Else check first and last digits num/10numDigits-1 and num % 10 if they do not match return false If they match, check more digits Apply algorithm recursively to: (num % 10numDigits-1)/10 and numDigits - 2 first digit – /10^5 = / = Last digit % 10 = remainder is 4 New number ( % )/10 = 4 remainder is 56654/10  5665 Length of integer: ceil(log10(n))

12 Recursion Example: Towers of Hanoi
Think Recursive algorithm Task Move disks from left peg to right peg When disk moved, must be placed on a peg Only one disk (top disk on a peg) moved at a time Larger disk may never be placed on a smaller disk

13 Recursion Example: Towers of Hanoi
Identify base case: If there is one disk move from A to C Inductive solution for n > 1 disks Move topmost n – 1 disks from A to B, using C for temporary storage Move final disk remaining on A to C Move the n – 1 disk from B to C using A for temporary storage

14 Towers of Hanoi: Solution
void hanoi(int n, const string& initNeedle, const string& endNeedle, const string& tempNeedle) { if (n == 1) cout << "move " << initNeedle << " to " << endNeedle << endl; else hanoi(n-1,initNeedle,tempNeedle,endNeedle); hanoi(n-1,tempNeedle,endNeedle,initNeedle); }

15 Towers of Hanoi: Solution
string beginneedle = "A", middleneedle = "B", endneedle = "C"; hanoi(3, beginneedle, endneedle, middleneedle); output The solution for n = 3 move A to C move A to B move C to B move B to A move B to C

16 Recursion Example: Towers of Hanoi
Note the graphical steps to the solution Stopped 2/27/06

17 Recursion Example: Parsing
Examples so far are direct recursion Function calls itself directly Indirect recursion occurs when A function calls other functions Some chain of function calls eventually results in a call to original function again An example of this is the problem of processing arithmetic expressions

18 Recursion Example: Parsing
Parser is part of the compiler Input to a compiler is characters Broken up into meaningful groups Identifiers, reserved words, constants, operators These units are called tokens Recognized by lexical analyzer Syntax rules applied

19 Recursion Example: Parsing
Parser generates a parse tree using the tokens according to rules below: An expression: term + term | term – term | term A term: factor * factor | factor / factor | factor A factor: ( expression ) | letter | digit Note the indirect recursion

20 Implementing Recursion: The Runtime Stack
Activation record created for each function call Activation records placed on run-time stack Recursive calls generate stack of similar activation records

21 Implementing Recursion: The Runtime Stack
When base case reached and successive calls resolved Activation records are popped off the stack


Download ppt "Recursion Gordon College CPS212"

Similar presentations


Ads by Google