Download presentation
Presentation is loading. Please wait.
Published byEzra Atkinson Modified over 9 years ago
1
2002-2009 Prentice Hall. All rights reserved. 1 Recursion (Section 7.13 & Exercise7.40 from ed.3) (Sections 6.15, 6.16 from ed.1) Many slides modified by Prof. L. Lilien (even many without an explicit message). Slides added by L.Lilien are © 2006-2009 Leszek T. Lilien. Permision to use for non-commercial purposes slides added by L.Lilien’s will be gladly granted upon a written (e.g., emailed) request.
2
2002-2009 Prentice Hall. All rights reserved. 2 7.13. Recursion Recursive methods - call themselves: –Directly –Indirectly Call others methods which call it Continually breaks problem down to simpler forms –Each method call divides the problem into two pieces: A piece that the method knows how to do A recursive call (a.k.a. recursion step) that solves a smaller problem In other words, each recursive method: –Waits till recursive call made by it finishes –Then finishes itself The method must converge in order to end recursion –Must include a “terminating condition” (see below)
3
2002-2009 Prentice Hall. All rights reserved. 3 7.13. Recursion (Cont.) Fig. 7.16 | Recursive evaluation of 5! Recursive Example 1: Factorial Calculation Recursive formula for factorial calculation: n! = n. (n – 1)! Termination conditions: 1! = 1 0! = 1
4
2002-2009 Prentice Hall. All rights reserved. 4 Outline FactorialTest.cs Program output: First, test to determine whether the terminating condition is true. The recursive call solves a slightly simpler problem (“number -1” vs. “number”) than the original calculation.
5
2002-2009 Prentice Hall. All rights reserved. 5 Run FactorialTest and watch Call Stack (code for FactorialTest is on the course web page) - Set up/open Call Stack window as follows: 1) set up a breakpoint at Line 11: Console.WriteLine("{0}! = {1}", 2) select Debug>>Start Debugging 3) if Call Stack window does not show up, select Debug>>Windows>> Call Stack 4) Use F11 (or Debug>>Step Into) to execute step-by-step © Leszek T. Lilien, 2009
6
2002-2009 Prentice Hall. All rights reserved. 6 ** READ LATER** 7.13. Recursion (Cont.) Common Programming Error 7.11 Infinite recursion (error!) occurs when the programmer either: 1)omits the base case (terminating condition), or 2)writes the recursion step incorrectly so that it does not converge on the base case Infinite recursion will eventually exhaust available memory. This error is analogous to the problem of an infinite loop in an iterative (nonrecursive) solution.
7
2002-2009 Prentice Hall. All rights reserved. 7 [from textbook edition 1] 6.15. Recursion Example 1: The Fibonacci Sequence Fibonacci Sequence –Recursion used to calculate F(n): F(0) = 0 F(1) = 1 F(n) = F(n - 1) + F(n - 2) Example – –Set of recursive calls to method Fibonacci [from Fig. 6.17 (ed.1)] return 1return 0 F( 1 )F( 0 )return 1 F( 3 ) F( 2 )F( 1 ) + return + Two terminating conditions. }
8
2002-2009 Prentice Hall. All rights reserved. 8 // FibonacciTest.cs [cf. ed.1-Fig. 6.16 (a Windows Forms application)] // Recursive Fibonacci method (uses Console application). using System; public class FibonacciTest { public static void Main(string[] args) { // Ask user to input an input number for calculations Console.Write("Enter an integer ( 1-25 ): "); int inputNumber = Convert.ToInt32(Console.ReadLine()); // Calculate Fibonacci number for the input number long fibonacciNumber = Fibonacci(inputNumber); // Output the Fibonacci number for the input number Console.WriteLine("Fibonacci({0}) = {1}", inputNumber, fibonacciNumber); } // Calculates Fibonacci number. // Static method, so can be called without first creating a // new instance of the FibonacciTest class (to which the method belongs). public static long Fibonacci(int number) { if (number == 0 || number == 1) return number; // Fibonacci(0)=0 and Fibonacci(1)=1 else return Fibonacci(number - 1) + Fibonacci(number - 2); } // end method Fibonacci } // end class FibonacciTest © Leszek T. Lilien, 2009 Main calls the Fibonacci method to get result The recursion ends when the number is 0 or 1 Fibonacci calls itself twice, to get the result as the sum of the two previous Fibonacci numbers
9
2002-2009 Prentice Hall. All rights reserved. 9 Output example 1: Enter an integer ( 1-25 ): 3 Fibonacci(3) = 2 Output example 2: Enter an integer ( 1-25 ): 22 Fibonacci(22) = 17711 © Leszek T. Lilien, 2009
10
2002-2009 Prentice Hall. All rights reserved. 10 Run FibonacciTest and watch Call Stack (copy code for FibonacciTest from page “-2” or from the course web page) - Set up/use Call Stack window as follows: 1) set up a breakpoint at Line 15: long fibonacciNumber = Fibonacci(inputNumber); 2) select Debug>>Start Debugging 3) if Call Stack window does not show up, select Debug>>Windows>> Call Stack 4) Use F11 (or Debug>>Step Into) to execute step-by-step © Leszek T. Lilien, 2009
11
2002-2009 Prentice Hall. All rights reserved. 11 [from textbook edition 1] 6.16. Recursion vs. Iteration Iteration –Uses repetition structures while, do/while, for, foreach –Continues until counter fails repetition condition Recursion –Uses selection structures if, if/else, switch –Repetition through method calls –Continues until a termination case reached (e.g., F(0) or F(1) for Fibonacci) –Creates duplicates of the variables Can consume a lot of memory and processor speed
12
2002-2009 Prentice Hall. All rights reserved. 12 Exercise 7.40. (p.330-ed.3) Recursion Example 3: Towers of Hanoi Background: –In a temple in the Far East, priests are attempting to move a stack of 64 disks from one peg to another –The legend: The world will end when the priests complete their task –The initial stack of 64 disks is threaded onto Peg 1 and arranged from bottom to top by decreasing size –The priests are attempting to move the stack from this peg to Peg 3 under the constraints that: Exactly one disk is moved at a time and At no time may a larger disk be placed above a smaller disk –Peg 2 is available for temporarily holding disks
13
2002-2009 Prentice Hall. All rights reserved. 13 Towers of Hanoi – Cont. Write an application to solve the Towers of Hanoi problem. Allow the user to enter the number of disks. Use a recursive Tower method with four parameters: a) the number of disks to be moved, b) the id of the initial peg (on which these disks are initially threaded), c) the id of the final peg (to which this stack of disks is to be moved), d) the id of the temporary peg (to be used as a temporary holding area). The application should display the precise instructions it will take to move the disks from the starting peg to the destination peg. — Example: To move a stack of 3 disks from Peg 1 to Peg 3, the application should display the following series of moves: 1 --> 3 (This notation means “Move the top disk from Peg 1 to Peg 3.”) 1 --> 2 3 --> 2 1 --> 3 2 --> 1 2 --> 3 1 --> 3
14
2002-2009 Prentice Hall. All rights reserved. 14 Towers of Hanoi – Cont. Developing an algorithm that displays the precise sequence of peg-to-peg disk transfers If we were to approach this problem with conventional methods (e.g. using iteration), we would rapidly find ourselves hopelessly knotted up in managing the disks If we attack the problem with recursion in mind, it immediately becomes quite easy to solve
15
2002-2009 Prentice Hall. All rights reserved. 15 Towers of Hanoi – Cont. Design -- Approach: 1) Moving n disks can be viewed recursively in terms of moving only n – 1 disks: a) Move n – 1 disks from Peg 1 to Peg 2, using Peg 3 as a temporary holding area b) Move the last disk (the largest) from Peg 1 to Peg 3 c) Move the n – 1 disks from Peg 2 to Peg 3, using Peg 1 as a temporary holding area 2) Terminating condition (base case ) : The process ends when the last task requires moving n = 1 disks This last task is accomplished by simply moving the disk (from the initial to the final peg) without the need for a temporary holding area
16
2002-2009 Prentice Hall. All rights reserved. 16 Towers of Hanoi – Cont.
17
2002-2009 Prentice Hall. All rights reserved. 17 Towers of Hanoi – Cont. Note: Don’t try to run the following program for values larger than 9 – you will use a lot of time and display (or printout) space. We’ll learn later how complexity theory explains this
18
2002-2009 Prentice Hall. All rights reserved. 18 Towers of Hanoi – Cont. Output for number of disks = 3: Enter number of disks ( 1-9 ): 3 1 --> 3 1 --> 2 3 --> 2 1 --> 3 2 --> 1 2 --> 3 1 --> 3
19
2002-2009 Prentice Hall. All rights reserved. 19 Towers of Hanoi – Cont. Output for number of disks = 4: Enter number of disks ( 1-9 ): 4 1 --> 2 1 --> 3 2 --> 3 1 --> 2 3 --> 1 3 --> 2 1 --> 2 1 --> 3 2 --> 3 2 --> 1 3 --> 1 2 --> 3 1 --> 2 1 --> 3 2 --> 3
20
2002-2009 Prentice Hall. All rights reserved. 20 The End
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.