 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.

Slides:



Advertisements
Similar presentations
Fundamentals of Computer Science Lecture 14: Recursion Instructor: Evan Korth New York University.
Advertisements

Lesson 19 Recursion CS1 -- John Cole1. Recursion 1. (n) The act of cursing again. 2. see recursion 3. The concept of functions which can call themselves.
Chapter 10 Recursion Instructor: alkar/demirer. Copyright ©2004 Pearson Addison-Wesley. All rights reserved.10-2 Recursive Function recursive functionThe.
Fundamentals of Computer Science Lecture 14: Recursion Instructor: Evan Korth New York University.
Slides prepared by Rose Williams, Binghamton University Chapter 11 Recursion.
1 CSCD 300 Data Structures Recursion. 2 Proof by Induction Introduction only - topic will be covered in detail in CS 320 Prove: N   i = N ( N + 1.
Slides prepared by Rose Williams, Binghamton University Chapter 11 Recursion.
 2002 Prentice Hall. All rights reserved. 1 Chapter 6 - Methods Outline Note: Inconsistent with textbook subsection numbering […] 6.14Recursion 6.15 Example.
Chapter 10 Recursion. Copyright © 2005 Pearson Addison-Wesley. All rights reserved Chapter Objectives Explain the underlying concepts of recursion.
 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 3 - Functions Outline 3.12Recursion 3.13Example Using Recursion: The Fibonacci Series 3.14Recursion.
FIT FIT1002 Computer Programming Unit 20 Recursion.
Copyright © 2003 Pearson Education, Inc. Slide 1.
ELC 310 Day 24. © 2004 Pearson Addison-Wesley. All rights reserved11-2 Agenda Questions? Problem set 5 Parts A Corrected  Good results Problem set 5.
Recursion A recursive function is a function that calls itself either directly or indirectly through another function. The problems that can be solved.
Chapter 11 Recursion. © 2004 Pearson Addison-Wesley. All rights reserved11-2 Recursion Recursion is a fundamental programming technique that can provide.
 2000 Prentice Hall, Inc. All rights reserved. Chapter 5 – Recursive Funtions From Deitel’s “C” Book 5.13Recursion 5.14Example Using Recursion: The Fibonacci.
Java How to Program, 9/e © Copyright by Pearson Education, Inc. All Rights Reserved.
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 122 – Data Structures Recursion Review.
Programming in C++ Language ( ) Lecture 6: Functions-Part2 Dr. Lubna Badri.
 2003 Prentice Hall, Inc. All rights reserved. 1 Functions and Recursion Outline Function Templates Recursion Example Using Recursion: The Fibonacci Series.
 Pearson Education, Inc. All rights reserved Recursion.
CHAPTER 02 Recursion Compiled by: Dr. Mohammad Omar Alhawarat.
Functions and an Introduction to Recursion.  Recursive function ◦ A function that calls itself, either directly, or indirectly (through another function)
Slides prepared by Rose Williams, Binghamton University ICS201 Lecture 19 : Recursion King Fahd University of Petroleum & Minerals College of Computer.
Lecture 12 Recursion part 1 Richard Gesick. Recursion A recursive method is a method that calls itself. A recursive method is capable of solving only.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
1 CS1120: Recursion. 2 What is Recursion? A method is said to be recursive if the method definition contains a call to itself A recursive method is a.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Functions (Recursion) Outline 5.13Recursion 5.14Example.
Principles of Programming - NI Simple Recursion Recursion is where a function calls itself. Concept of recursive function: A recursive function is.
Review Introduction to Searching External and Internal Searching Types of Searching Linear or sequential search Binary Search Algorithms for Linear Search.
Chapter 8 Recursion Modified.
Chapter 4 Recursion. Copyright © 2004 Pearson Addison-Wesley. All rights reserved.1-2 Chapter Objectives Explain the underlying concepts of recursion.
 2007 Pearson Education, Inc. All rights reserved C Functions -Continue…-
11-1 Recursive Thinking A recursive definition is one which uses the word or concept being defined in the definition itself When defining an English word,
 2005 Pearson Education, Inc. All rights reserved Recursion.
Dale Roberts CSCI N305 Functions Recursion Department of Computer and Information Science, School of Science, IUPUI.
1 Recursion Recursive method –Calls itself (directly or indirectly) through another method –Method knows how to solve only a base case –Method divides.
Lecture 7 b Recursion is a fundamental programming technique that can provide an elegant solution to certain kinds of problems b Today: thinking in a recursive.
Java Programming: Guided Learning with Early Objects Chapter 11 Recursion.
 Prentice Hall. All rights reserved. 1 CS 1120 – Computer Science II Recursion (Ch.15) Many slides modified by Prof. L. Lilien (even many without.
1 Recursion Recursion is a powerful programming technique that provides elegant solutions to certain problems. Chapter 11 focuses on explaining the underlying.
Principles of Programming - NI Simple Recursion Recursion is where a function calls itself. Concept of recursive function: A recursive function is.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 12 Recursion.
Recursion Chapter 17 Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013.
C++ Programming Lecture 12 Functions – Part IV
 Prentice Hall. All rights reserved. 1 CS 1120 – Computer Science II Recursion (Ch.15) Many slides modified by Prof. L. Lilien (even many without.
Java How to Program, 10/e Late Objects Version © Copyright by Pearson Education, Inc. All Rights Reserved.
1 CS1120: Recursion. 2 What is Recursion? A method is said to be recursive if the method definition contains a call to itself A recursive method is a.
chap10 Chapter 10 Recursion chap10 2 Recursive Function recursive function The recursive function is a kind of function that calls.
Recursion by Ender Ozcan. Recursion in computing Recursion in computer programming defines a function in terms of itself. Recursion in computer programming.
Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with C++ Early Objects Eighth Edition by Tony Gaddis,
1 CSC 143 Recursion [Reading: Chapter 17]. 2 Recursion  A recursive definition is one which is defined in terms of itself.  Example:  Sum of the first.
Recursion.
Chapter 10 Recursion Instructor: Yuksel / Demirer.
RECURSION.
Chapter 7 - Methods Outline Note: Inconsistent with textbook subsection numbering […] 7.13 Recursion […]
Recursive Thinking Chapter 9 introduces the technique of recursive programming. As you have seen, recursive programming involves spotting smaller occurrences.
Java Software Structures: John Lewis & Joseph Chase
15 Recursion.
Recursive Thinking Chapter 9 introduces the technique of recursive programming. As you have seen, recursive programming involves spotting smaller occurrences.
MSIS 655 Advanced Business Applications Programming
Chapter 12 Recursion (methods calling themselves)
CS1120: Recursion.
Recursion Data Structures.
25 Searching and Sorting Many slides modified by Prof. L. Lilien (even many without an explicit message indicating an update). Slides added or modified.
Dr. Sampath Jayarathna Cal Poly Pomona
Programming Fundamentals Lecture #7 Functions
Presentation transcript:

 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 © 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., ed) request.

 Prentice Hall. All rights reserved 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)

 Prentice Hall. All rights reserved Recursion (Cont.) Fig | Recursive evaluation of 5! Recursive Example 1: Factorial Calculation Recursive formula for factorial calculation: n! = n. (n – 1)! Termination conditions: 1! = 1 0! = 1

 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.

 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

 Prentice Hall. All rights reserved. 6 ** READ LATER** 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.

 Prentice Hall. All rights reserved. 7 [from textbook edition 1] 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 (ed.1)] return 1return 0 F( 1 )F( 0 )return 1 F( 3 ) F( 2 )F( 1 ) + return + Two terminating conditions. }

 Prentice Hall. All rights reserved. 8 // FibonacciTest.cs [cf. ed.1-Fig (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

 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) = © Leszek T. Lilien, 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

 Prentice Hall. All rights reserved. 11 [from textbook edition 1] 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

 Prentice Hall. All rights reserved. 12 Exercise (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

 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 --> > > > > > 3

 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

 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

 Prentice Hall. All rights reserved. 16 Towers of Hanoi – Cont.

 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

 Prentice Hall. All rights reserved. 18 Towers of Hanoi – Cont. Output for number of disks = 3: Enter number of disks ( 1-9 ): > > > > > > > 3

 Prentice Hall. All rights reserved. 19 Towers of Hanoi – Cont. Output for number of disks = 4: Enter number of disks ( 1-9 ): > > > > > > > > > > > > > > > 3

 Prentice Hall. All rights reserved. 20 The End