Presentation is loading. Please wait.

Presentation is loading. Please wait.

C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 16: Recursion.

Similar presentations


Presentation on theme: "C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 16: Recursion."— Presentation transcript:

1 C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 16: Recursion

2 C++ Programming: Program Design Including Data Structures, Fourth Edition2 Objectives In this chapter, you will: Learn about recursive definitions Explore the base case and the general case of a recursive definition Discover what is a recursive algorithm Learn about recursive functions Explore how to use recursive functions to implement recursive algorithms

3 C++ Programming: Program Design Including Data Structures, Fourth Edition3 Recursive Definitions – n! Recursion −solving a problem by reducing it to smaller versions of itself 0! = 1(1) n! = n x (n-1)! if n > 0(2) The definition of factorial in equations (1) and (2) is called a recursive definition −Equation (1) is called the base case −Equation (2) is called the general case

4 C++ Programming: Program Design Including Data Structures, Fourth Edition4 Recursive Definitions (continued) Recursive definition −defining a problem in terms of a smaller version of itself Every recursive definition must have one (or more) base cases The general case must eventually reduce to a base case The base case stops the recursion

5 C++ Programming: Program Design Including Data Structures, Fourth Edition5 Recursive Definitions (continued) Recursive algorithm −finds a solution by reducing problem to smaller versions of itself Must have one (or more) base cases General solution must eventually reduce to a base case Recursive function −a function that calls itself Recursive algorithms are implemented using recursive functions

6 C++ Programming: Program Design Including Data Structures, Fourth Edition6 Recursive Definitions (continued) Think of a recursive function as having infinitely many copies of itself −After completing a particular recursive call: Control goes back to the calling environment, which is the previous call Execution begins from the point immediately following the recursive call

7 Every call to a recursive function has its own code and its own set of parameters and local variables cout << fact(4) << endl;

8 Factorial using Recursion my version long rFactorial( long n ) { // base cases: n = 0, n = 1 // general case: n > 1 if ( n == 0 || n == 1 ) return 1; else return n * rFactorial( n-1 ); } C++ Programming: Program Design Including Data Structures, Fourth Edition8

9 9 Direct and Indirect Recursion Directly recursive −a function that calls itself Indirectly recursive −a function that calls another function and eventually results in the original function call Tail recursive function −function in which the last statement executed is the recursive call −Example: the function fact

10 C++ Programming: Program Design Including Data Structures, Fourth Edition10 Infinite Recursion Infinite recursion −every recursive call results in another recursive call −In theory, infinite recursion executes forever Because computer memory is finite: −Function executes until the system runs out of memory −Results in an abnormal program termination

11 C++ Programming: Program Design Including Data Structures, Fourth Edition11 Infinite Recursion (continued) To design a recursive function: −Understand problem requirements −Determine limiting conditions −Identify base cases and provide a direct solution to each base case −Identify general cases and provide a solution to each general case in terms of smaller versions of itself

12 C++ Programming: Program Design Including Data Structures, Fourth Edition12 Problem Solving Using Recursion

13 C++ Programming: Program Design Including Data Structures, Fourth Edition13 Problem Solving Using Recursion (continued)

14 cout << largest(list, 0, 3) << endl;

15 C++ Programming: Program Design Including Data Structures, Fourth Edition15 Problem Solving Using Recursion (continued)

16 cout << rFibNum(2, 3, 5) << endl; first second nth

17 C++ Programming: Program Design Including Data Structures, Fourth Edition17 Problem Solving Using Recursion Towers of Hanoi

18 Towers of Hanoi - background C++ Programming: Program Design Including Data Structures, Fourth Edition18 Origins The puzzle was invented by the French mathematician Édouard Lucas in 1883. There is a legend about a Vietnamese temple which contains a large room with three time-worn posts in it surrounded by 64 golden disks. The priests of Hanoi, acting out the command of an ancient prophecy, have been moving these disks, in accordance with the rules of the puzzle, since that time. The puzzle is therefore also known as the Tower of Brahma puzzle. According to the legend, when the last move of the puzzle is completed, the world will end.FrenchmathematicianÉdouard LucasVietnameseHanoiBrahma It is not clear whether Lucas invented this legend or was inspired by it. If the legend were true, and if the priests were able to move disks at a rate of one per second, using the smallest number of moves, it would take them 2 64 −1 seconds or roughly 585 billion years; [1] it would take 18,446,744,073,709,551,615 turns to finish.billion [1] There are many variations on this legend. For instance, in some tellings, the temple is a monastery and the priests are monks. The temple or monastery may be said to be in different parts of the world — including Hanoi, Vietnam, and may be associated with any religion. In some versions, other elements are introduced, such as the fact that the tower was created at the beginning of the world, or that the priests or monks may make only one move per day. monasterymonksHanoiVietnamreligion The Flag Tower of Hanoi may have served as the inspiration for the name.Flag Tower of Hanoi

19 Towers of Hanoi - Solution C++ Programming: Program Design Including Data Structures, Fourth Edition19 Simple solution The following solution is a simple solution for the toy puzzle. Alternate moves between the smallest piece and a non-smallest piece. When moving the smallest piece, always move it in the same direction (to the right if the starting number of pieces is even, to the left if the starting number of pieces is odd). If there is no tower in the chosen direction, move the piece to the opposite end, but then continue to move in the correct direction. For example, if you started with three pieces, you would move the smallest piece to the opposite end, then continue in the left direction after that. When the turn is to move the non-smallest piece, there is only one legal move. Doing this should complete the puzzle using the least amount of moves to do so.

20

21 C++ Programming: Program Design Including Data Structures, Fourth Edition21 Problem Solving Using Recursion (continued)

22 C++ Programming: Program Design Including Data Structures, Fourth Edition22 Recursion or Iteration? There are usually two ways to solve a particular problem: Iteration (looping) Recursion Which method is better—iteration or recursion? In addition to the nature of the problem, the other key factor in determining the best solution method is efficiency

23 C++ Programming: Program Design Including Data Structures, Fourth Edition23 Recursion or Iteration? (continued) Whenever a function is called −Memory space for its formal parameters and (automatic) local variables is allocated When the function terminates −That memory space is then deallocated Every (recursive) call has its own set of parameters and (automatic) local variables

24 C++ Programming: Program Design Including Data Structures, Fourth Edition24 Recursion or Iteration? (continued) Overhead associated with executing a (recursive) function in terms of: Memory space Computer time A recursive function executes more slowly than its iterative counterpart

25 C++ Programming: Program Design Including Data Structures, Fourth Edition25 Recursion or Iteration? (continued) On slower computers, especially those with limited memory space −The slow execution of a recursive function would be visible Today’s computers are fast and have inexpensive memory −Speed of execution of a recursive function is not noticeable

26 C++ Programming: Program Design Including Data Structures, Fourth Edition26 Recursion or Iteration? (continued) Choice between the two alternatives depends on the nature of the problem For problems such as mission control systems, efficiency is critical and dictates the solution method An iterative solution is more obvious and easier to understand than a recursive solution If the definition of a problem is inherently recursive, consider a recursive solution

27 Factorial – Iterative Solution long iFactorial( long n ) { // base cases: n = 0, n = 1 // general case: n! = n * n-1 * n-2 *... 2 if ( n == 0 || n == 1 ) return 1; long factorial = n; for ( int j = n-1; j>1; j-- ) factorial *= j; return factorial; } C++ Programming: Program Design Including Data Structures, Fourth Edition27

28 Fibonacci Sequence – Iterative Solution long iFibonacci( int first, int second, int nth ) { //fibonacci(first, second, n) (where n is the nth element in the sequence) is // if n = 1, first // if n = 2, second // if n > 2, kth = (k-2)th + (k-1)th repeated until kth = nth if ( nth == 1 ) return first; else if ( nth == 2 ) return second; long nthValue = 0; for (int j=3; j <= nth; j++) { nthValue = first + second; first = second; second = nthValue; } return nthValue; } C++ Programming: Program Design Including Data Structures, Fourth Edition28

29 C++ Programming: Program Design Including Data Structures, Fourth Edition29 Programming Example: Converting a Number from Binary to Decimal Use recursion to convert a non-negative integer in decimal format (base 10) into the equivalent binary number (base 2) Define some terms: −Let x be an integer −Rightmost bit of x remainder of x after division by 2 Rightmost bit of 33 is 1 Rightmost bit of 28 is 0 2 5 2 4 2 3 2 2 2 1 2 0 32 16 8 4 2 1 10 0 0 0 1 0 1 1 1 0 0

30 C++ Programming: Program Design Including Data Structures, Fourth Edition30 Programming Example (continued) To find the binary representation of 35: −Divide 35 by 2 The quotient is 17 and the remainder is 1 −Divide 17 by 2 The quotient is 8 and the remainder is 1 −Divide 8 by 2 The quotient is 4 and the remainder is 0 −Continue process until quotient becomes 0 Rightmost bit of 35 cannot be printed until we have printed the rightmost bit of 17

31 C++ Programming: Program Design Including Data Structures, Fourth Edition31 Programming Example (continued) Binary representation of 35 is the binary representation of 17 (35/2) followed by the rightmost bit of 35

32 decToBin(13, 2);

33 C++ Programming: Program Design Including Data Structures, Fourth Edition33 Summary Recursion −process of solving a problem by reducing it to smaller versions of itself Recursive definition −defines a problem in terms of smaller versions of itself −Has one or more base cases Recursive algorithm −solves a problem by reducing it to smaller versions of itself −Has one or more base cases

34 C++ Programming: Program Design Including Data Structures, Fourth Edition34 Summary (continued) The solution to the problem in a base case is obtained directly Recursive function −function that calls itself −must have one or more base cases Recursive algorithms are implemented using recursive functions The general solution breaks the problem into smaller versions of itself

35 C++ Programming: Program Design Including Data Structures, Fourth Edition35 Summary (continued) The general case must eventually be reduced to a base case −The base case stops the recursion Directly recursive −a function calls itself Indirectly recursive −a function calls another function and eventually calls the original Tail recursive −the last statement executed is the recursive call


Download ppt "C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 16: Recursion."

Similar presentations


Ads by Google