Presentation is loading. Please wait.

Presentation is loading. Please wait.

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

Similar presentations


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

1 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 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 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 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 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 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 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 8 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Figure 12.2 Trace of function power

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

10 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 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 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 13 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Figure 12.3 Trace of function reverse

14 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 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 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 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 18 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Figure 12.5 Trace of factorial (3)

19 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 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 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 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 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 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 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 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 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 28 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Listing 12.9 Recursive binary search function

29 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 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 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 32 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Case Study: Algorithm 1. If n is 1 1.1 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 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 12.10 Recursive function tower

34 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 12.10 Recursive function tower (continued)

35 35 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Listing 12.11 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 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


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

Similar presentations


Ads by Google