Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 12: Recursion Problem Solving, Abstraction, and Design using C++

Slides:



Advertisements
Similar presentations
Lecture 22: Arrays (cont). 2 Lecture Contents: t Searching in array: –linear search –binary search t Multidimensional arrays t Demo programs t Exercises.
Advertisements

Factorial Recursion stack Binary Search Towers of Hanoi
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.
Chapter 17 Recursion. Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display Mathematical Definition: RunningSum(1)
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with C++ Early Objects Sixth Edition Chapter 14: Recursion by.
Programming with Recursion
Chapter 10 Recursion Dr. Jiung-yao Huang Dept. Comm. Eng. Nat. Chung Cheng Univ. TA: 鄭筱親 陳昱豪.
Slides prepared by Rose Williams, Binghamton University Chapter 11 Recursion.
Recursion. 2 CMPS 12B, UC Santa Cruz Solving problems by recursion How can you solve a complex problem? Devise a complex solution Break the complex problem.
Chapter 10 Recursion. Copyright © 2005 Pearson Addison-Wesley. All rights reserved Chapter Objectives Explain the underlying concepts of recursion.
1 Chapter 18 Recursion Dale/Weems/Headington. 2 Chapter 18 Topics l Meaning of Recursion l Base Case and General Case in Recursive Function Definitions.
1 Chapter 7 Recursion. 2 What Is Recursion? l Recursive call A method call in which the method being called is the same as the one making the call l Direct.
Recursion A recursive function is a function that calls itself either directly or indirectly through another function. The problems that can be solved.
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with Java: Early Objects Third Edition by Tony Gaddis Chapter.
Chapter 2 Recursion: The Mirrors. © 2005 Pearson Addison-Wesley. All rights reserved2-2 Recursive Solutions Recursion is an extremely powerful problem-
CENG 7071 Recursion. CENG 7072 Recursion Recursion is a technique that solves a problem by solving a smaller problem of the same type. A recursive function.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 10: Recursion Problem Solving and Program Design in C 5th Edition.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 19: Recursion.
1 C++ Plus Data Structures Nell Dale Chapter 7 Programming with Recursion Slides by Sylvia Sorkin, Community College of Baltimore County - Essex Campus.
Recursion Chapter 7 Copyright ©2012 by Pearson Education, Inc. All rights reserved.
Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with C++ Early Objects Eighth Edition by Tony Gaddis,
Recursion Chapter Nature of Recursion t Problems that lend themselves to a recursive solution have the following characteristics: –One or more.
Chapter 2 Recursion: The Mirrors CS Data Structures Mehmet H Gunes Modified from authors’ slides.
Department of Computer Science Data Structures Using C++ 2E Chapter 6: Recursion Learn about recursive Definitions Algorithms Functions Explore the base.
Recursion.
© 2010 Pearson Addison-Wesley. All rights reserved. Addison Wesley is an imprint of Chapter 15: Recursion Starting Out with Java: From Control Structures.
Copyright © 2011 Pearson Education, Inc. Starting Out with Java: Early Objects Fourth Edition by Tony Gaddis Chapter 14: Recursion.
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 12 Recursion.
Data Structures and Abstractions with Java, 4e Frank Carrano
Programming Principles II Lecture Notes 5 Recursion Andreas Savva.
Chapter 12 Recursion, Complexity, and Searching and Sorting
1 Chapter 13 Recursion. 2 Chapter 13 Topics l Meaning of Recursion l Base Case and General Case in Recursive Function Definitions l Writing Recursive.
1 Recursion. 2 Chapter 15 Topics  Meaning of Recursion  Base Case and General Case in Recursive Function Definitions  Writing Recursive Functions with.
CSE 1342 Programming Concepts Recursion. Overview of Recursion nRecursion is present when a function is defined in terms of itself. nThe factorial of.
1 C++ Plus Data Structures Nell Dale Chapter 7 Programming with Recursion Modified from the slides by Sylvia Sorkin, Community College of Baltimore County.
Recursion Textbook chapter Recursive Function Call a recursive call is a function call in which the called function is the same as the one making.
1 C++ Plus Data Structures Nell Dale Chapter 7 Programming with Recursion Slides by Sylvia Sorkin, Community College of Baltimore County - Essex Campus.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley. Ver Chapter 2: Recursion: The Mirrors Data Abstraction & Problem Solving.
1 7.Algorithm Efficiency What to measure? Space utilization: amount of memory required  Time efficiency: amount of time required to process the data Depends.
Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with Programming Logic & Design Second Edition by Tony Gaddis.
Computer Science Department Data Structure & Algorithms Lecture 8 Recursion.
Review Introduction to Searching External and Internal Searching Types of Searching Linear or sequential search Binary Search Algorithms for Linear Search.
Chapter 13 Recursion. Learning Objectives Recursive void Functions – Tracing recursive calls – Infinite recursion, overflows Recursive Functions that.
Chapter 4 Recursion. Copyright © 2004 Pearson Addison-Wesley. All rights reserved.1-2 Chapter Objectives Explain the underlying concepts of recursion.
Chapter 13 Recursion. Copyright © 2005 Pearson Addison-Wesley. All rights reserved. Slide 2 Overview Recursive Functions for Tasks(13.1) Recursive Functions.
CSC 221: Recursion. Recursion: Definition Function that solves a problem by relying on itself to compute the correct solution for a smaller version of.
Java Programming: Guided Learning with Early Objects Chapter 11 Recursion.
1 Recursion. 2 Chapter 15 Topics  Meaning of Recursion  Base Case and General Case in Recursive Function Definitions  Writing Recursive Functions with.
Chapter 7 Programming with Recursion. What Is Recursion? Recursive call A method call in which the method being called is the same as the one.
1 Chapter 8 Recursion. 2 Objectives  To know what is a recursive function and the benefits of using recursive functions (§8.1).  To determine the base.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Recursion.
CS162 - Topic #10 Lecture: Recursion –The Nature of Recursion –Tracing a Recursive Function –Work through Examples of Recursion Programming Project –Discuss.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 14 Recursion.
chap10 Chapter 10 Recursion chap10 2 Recursive Function recursive function The recursive function is a kind of function that calls.
CS 116 Object Oriented Programming II Lecture 13 Acknowledgement: Contains materials provided by George Koutsogiannakis and Matt Bauer.
Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with C++ Early Objects Eighth Edition by Tony Gaddis,
1 7.Algorithm Efficiency These factors vary from one machine/compiler (platform) to another  Count the number of times instructions are executed So, measure.
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.
Lecture 11 Recursion. A recursive function is a function that calls itself either directly, or indirectly through another function; it is an alternative.
1 Dr. Chow-Sing LinRecursion - CH 10 Problem Solving and Program Design in C Chapter 9 Recursion Chow-Sing Lin.
Chapter 9 Recursion. Copyright ©2004 Pearson Addison-Wesley. All rights reserved.10-2 Recursive Function recursive functionThe recursive function is –a.
Recursion CENG 707.
Chapter 10 Recursion Instructor: Yuksel / Demirer.
Chapter 10 Recursion Dr. Jiung-yao Huang Dept. Comm. Eng.
Recursion: The Mirrors
Recursion Chapter 12.
Programming with Recursion
Chapter 18 Recursion.
Presentation transcript:

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 12: Recursion Problem Solving, Abstraction, and Design using C++ 6e by Frank L. Friedman and Elliot B. Koffman

2 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 12.1 Nature of Recursion Recursive function: function that calls itself Problems that lend themselves to a recursive solution have the following characteristics: –One or more simple case of the problem have a straightforward, non-recursive solution (stopping case) –Other cases can be reduced to one or more problems that are closer to a stopping case –Eventually the problem can be reduced to stopping cases only, which are easy to solve.

3 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley To Solve a Recursive Problem 1. Try to express the problem as a simpler version of itself. 2. Determine the stopping cases. 3. Determine the recursive steps. If the stopping case is reached Solve the problem else Split the problem into simpler cases using recursion.

4 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Splitting a Problem into Smaller Problems Size n Problem Size 1 problem Size n-1 Problem Size 1 problem Size n-2 Problem Size 1 problem Size 2 Problem Size 1 problem Size 1 problem...

5 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Power by Multiplication Raise 6 to the power of 3 –Raise 6 to the power of 2 –Multiply the result by 6 Raise 6 to the power of 2 –Raise 6 to the power of 1 –Multiply the result by 6 End up multiplying 6 * 6 * 6

6 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Listing 12.1 Recursive Function power // FILE: power.cpp // Recursive power function // Raises its first argument to the power // indicated by its second argument. // Pre:m and n are defined and n > 0. // Post:Returns m raised to power n. int power (int m, int n)// IN: raise m to power n { if (n <= 1) return m;// stopping case else return m * power (m, n - 1);// recursion }

7 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 12.2 Tracing Recursive Functions Use hand tracing to see how algorithm works Very useful in recursion Activation frame corresponds to a function call with argument values shown

8 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Figure 12.2 Trace of function power

9 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Listing 12.2 Recursive function power with tracing

10 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Recursive Function with No Return Value If statement with some stopping condition –(next != ‘*’) When FALSE stopping case is reached –recursive step is finished –falls back to previous calls (if any) –trace of reverse

11 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley // File: reverseTest // Tests a function which displays keyboard input in reverse #include using namespace std; // Function prototype void reverse(); int main () { reverse();// Revers the keyboard input cout << endl; return 0; } Listing 12.3 Function reverse

12 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley // Displayes keyboard input in reverse void reverse() { char next; cout << "Next character or * to stop: "; cin >> next; if (next != ‘*’) { reverse();// recursive case cout << next;// Display next after return } Listing 12.3 Function reverse (continued)

13 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Figure 12.3 Trace of function reverse

14 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Stack for Function Calls How does C++ keep track of n and next ? Uses a data structure called a stack –Think of a stack of trays in a cafeteria –Each time a function is called arguments and local variable values are pushed onto the stack –Only top values (i.e. from the top-most function) are used when needed (popping) Example of calls to reverse

15 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Argument Stacks in C++ Compiler maintains a single stack for function arguments and return points Each time a call to a function occurs, all of its arguments and local variables are pushed onto the stack, along with the memory address of the calling statement Only one copy of the function body is in memory, though there can be multiple copies of a function’s arguments on the stack

16 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 12.3 Recursive Mathematical Functions Many mathematical functions are defined recursively –factorial (n!) of a number 0! = 1 n! is n  (n-1)!, for n > 0 So 4! = 4  3! = 4  3  2! = 4  3  2  1 or 24

17 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Listing 12.4 Recursive factorial Function // File: factorial.cpp // Recursvie factorial function // Computes N! // Pre: n is defined and n >= 0. // Post: none. // Returns: n! int factorial (int n) { if (n <= 0) return 1; else return n * factorial (n-1); }

18 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Figure 12.5 Trace of factorial (3)

19 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Listing 12.5 Iterative Factorial Function // File: factorialI.cpp // Iterative factorial function // Computes n! // Pre: n is defined and n >= 0; // Post: none // Returns: n! int factorialI (int n) { // Local data int factorial; // accumulating product factorial = 1; for (int i = 2; i <= n; i++) factorial *= i; return factorial; }

20 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Listing 12.6 Recursive fibonacci Function // File: fibonacci.cpp // Recursive fbonacci number function // Pre: n is defined and n > 0. // Post: None // Returns: The nth Fibonacci number. int fibonacci (int n) { if (n <= 2) return 1; else return fibonacci(n - 2) + fibonacci(n - 1); }

21 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 12.4 Recursive Functions with Array Arguments May be able to solve a problem involving an n-element array by splitting into a problem involving an n-1 element array and a single array element Normally, array with one element is stopping case E.g. Find the sum of n-element array. –Stopping case is a 1-element array: sum is value stored in element with subscript 0

22 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley // File: findSumTest.cpp // Program and recursive function to sum an array’s elements #include using namespace std; // Function prototype int findSum(int[], int); int main() { const int SIZE = 10; int x[SIZE]; // array of 10 elements int sum1; // result of recursive sum int sum2; // calculated sum // Fill array x for (int i = 0; i < SIZE; i++) x[i] = i + 1;// store 1, 2, 3,... in x Listing 12.6 Function findSum

23 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley // Calulate sum two ways sum1 = findSum(x, SIZE); sum2 = (SIZE * (SIZE + 1)) / 2; cout << "Recursive sum is " << sum1 << endl; cout << "Calculated sum is " << sum2 << endl; return 0; } // Finds the sum of integers in an n-element array int findSum(int x[], int n) { if (n == 1) return x[0]; // stopping case else return x[n-1] + findSum(x, n-1); // recursive step } Listing 12.6 Function findSum (continued)

24 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Case Study: Binary Search Problem –If the elements of the array being searched have been sorted, we can make use of a more efficient search algorithm known as binary search. In binary search, we’re able to reduce the problem of searching an n-element array to a search involving an n/2 element array. Write a function that implements the binary search algorithm.

25 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Case Study: Analysis Function Interface –Input Parameters table// array to search target// target value first// index of first element of subarray last// index of last element of subarray –Function Result if found, location of target value in array if not found, -1

26 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Case Study: Design Two stopping cases –the array bounds are improper (first > last) returns -1 to indicate target not found –the middle value is the target value returns the index of the found target value

27 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Binary Search Algorithm 1. Compute the subscript of the middle element of the array 2. If the array bounds are improper 3. target not present, return -1 else if target is the middle value 4. Return subscript of middle value else if target is less than the middle value 5. Search subarray with indices first through middle-1 else 6. Search subarray with indices middle+1 through last.

28 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Listing 12.9 Recursive binary search function

29 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 12.5 Problem Solving with Recursion Case Study: The Towers of Hanoi Problem Statement –Solve the Towers of Hanoi problem for n disks, where n is the number of disks to be moved from tower A to tower C

30 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Case Study: Analysis Solution is a printed list of each disk move. Recursive function that can be used to move any number of disks from one tower to the other tower. Only one disk may be moved at a time - must be top disk on a tower A larger disk cannot be placed on top a smaller disk Stopping case involves moving one disk only

31 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Case Study: Function Interface Input Parameters –int n// number of disks to be moved –char fromTower// the from tower –char toTower// the to tower –char auxTower// the auxiliary tower Function Results –Displays the list of moves required to move the disks

32 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Case Study: Algorithm 1. If n is Move disk 1 from the from tower to the to tower. else 1.2 Move n-1 disks from the from tower to the auxiliary tower. 1.3 Move disk n from the from tower to the to tower. 1.4 Move n-1 disks from the auxiliary tower to the to tower.

33 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley // File: tower.cpp // Recursive tower of hanoi function #include using namespace std; // Function prototype void tower(char, char, char, int); int main() { int numDisks; // input - number of disks cout << "How many disks: "; cin >> numDisks; tower('A', 'C', 'B', numDisks); return 0; } Listing Recursive function tower

34 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley void tower (char fromTower, char toTower, char auxTower, int n) { if (n == 1) cout << "Move disk 1 from tower " << fromTower << " to tower " << toTower << endl; else { tower(fromTower, auxTower, toTower, n-1); cout << "Move disk " << n << " from tower "<< fromTower << " to tower " << toTower << endl; tower(auxTower, toTower, fromTower, n-1); } } // end tower Listing Recursive function tower (continued)

35 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Listing Trace of tower(‘A’, ‘C’, ‘B’, 3); Move disk 1 from tower A to tower C Move disk 2 from tower A to tower B Move disk 1 from tower C to tower B Move disk 3 from tower A to tower C Move disk 1 from tower B to tower A Move disk 2 from tower B to tower C Move disk 1 from tower A to tower C

36 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 12.6 Common Programming Errors Stopping condition for recursive functions Missing return statements Optimizations for recursive functions Using a debugger with recursive functions