Chapter 14: Recursion Starting Out with C++ Early Objects

Slides:



Advertisements
Similar presentations
C++ Programming:. Program Design Including
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.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved Chapter 19 Recursion.
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with C++ Early Objects Sixth Edition Chapter 14: Recursion by.
Chapter 19 Recursion.
Chapter 15 Recursive Algorithms. 2 Recursion Recursion is a programming technique in which a method can call itself to solve a problem A recursive definition.
Starting Out with C++: Early Objects 5/e © 2006 Pearson Education. All Rights Reserved Starting Out with C++: Early Objects 5 th Edition Chapter 14 Recursion.
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with Java: Early Objects Third Edition by Tony Gaddis Chapter.
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 1 Chapter 20 Recursion.
Introduction to Programming (in C++) Recursion Jordi Cortadella, Ricard Gavaldà, Fernando Orejas Dept. of Computer Science, UPC.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 19: Recursion.
Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with C++ Early Objects Eighth Edition by Tony Gaddis,
Copyright 2003 Scott/Jones Publishing Standard Version of Starting Out with C++, 4th Edition Chapter 19 Recursion.
Chapter 14: Recursion Starting Out with C++ Early Objects
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 17: Recursion.
Chapter 13 Recursion. Topics Simple Recursion Recursion with a Return Value Recursion with Two Base Cases Binary Search Revisited Animation Using 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.
15-1 Chapter-18: Recursive Methods –Introduction to Recursion –Solving Problems with Recursion –Examples of Recursive Methods.
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 12 Recursion.
Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with Programming Logic & Design Second Edition by Tony Gaddis.
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.
Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with Programming Logic & Design Second Edition by Tony Gaddis.
Review Introduction to Searching External and Internal Searching Types of Searching Linear or sequential search Binary Search Algorithms for Linear Search.
Java Programming: Guided Learning with Early Objects Chapter 11 Recursion.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 15 * Recursive Algorithms.
Recursion. Circular Definition (not useful) E.g., E.g., Projenitor: one who produces an offspring Projenitor: one who produces an offspring Offspring:
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.
Starting Out with C++, 3 rd Edition Chapter 19 Recursion.
JAVA: An Introduction to Problem Solving & Programming, 7 th Ed. By Walter Savitch ISBN © 2015 Pearson Education, Inc., Upper Saddle River,
Maitrayee Mukerji. Factorial For any positive integer n, its factorial is n! is: n! = 1 * 2 * 3 * 4* ….* (n-1) * n 0! = 1 1 ! = 1 2! = 1 * 2 = 2 5! =
CS 116 Object Oriented Programming II Lecture 13 Acknowledgement: Contains materials provided by George Koutsogiannakis and Matt Bauer.
Program Development and Design Using C++, Third Edition
Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with C++ Early Objects Eighth Edition by Tony Gaddis,
Chapter 9 Recursion. Copyright ©2004 Pearson Addison-Wesley. All rights reserved.10-2 Recursive Function recursive functionThe recursive function is –a.
Recursion You may have seen mathematical functions defined using recursion Factorial(x) = 1 if x
Recursion Powerful Tool
CS212: Data Structures and Algorithms
Chapter Topics Chapter 16 discusses the following main topics:
Chapter 19: Recursion.
Recursion CSE 2320 – Algorithms and Data Structures
Recursion Version 1.0.
Recursion The programs discussed so far have been structured as functions that invoke one another in a disciplined manner For some problems it is useful.
Topic 6 Recursion.
Recursion what is it? how to build recursive algorithms
Chapter 15 Recursion.
Chapter 10 Recursion Instructor: Yuksel / Demirer.
Recursion DRILL: Please take out your notes on Recursion
OBJECT ORIENTED PROGRAMMING II LECTURE 23 GEORGE KOUTSOGIANNAKIS
Recursion A problem solving technique where an algorithm is defined in terms of itself A recursive method is a method that calls itself A recursive algorithm.
Decrease-and-Conquer Approach
Recursion Chapter 12.
Chapter 15 Recursion.
Chapter 9: Searching, Sorting, and Algorithm Analysis
Chapter 19 Recursion.
Recursion CSE 2320 – Algorithms and Data Structures
Chapter 14: Recursion Starting Out with C++ Early Objects
Recursion "To understand recursion, one must first understand recursion." -Stephen Hawking.
Applied Algorithms (Lecture 17) Recursion Fall-23
Recursion Chapter 11.
Chapter 14: Recursion Starting Out with C++ Early Objects
Chapter 17: Linked Lists Starting Out with C++ Early Objects
Recursion Chapter 18.
7.Recursion Recursion is the name given for expression anything in terms of itself. Recursive function is a function which calls itself until a particular.
Basics of Recursion Programming with Recursion
Java Programming: Chapter 9: Recursion Second Edition
Yan Shi CS/SE 2630 Lecture Notes
Chapter 19: Recursion.
Dr. Sampath Jayarathna Cal Poly Pomona
Chapter 3 :Recursion © 2011 Pearson Addison-Wesley. All rights reserved.
Presentation transcript:

Chapter 14: Recursion Starting Out with C++ Early Objects Ninth Edition by Tony Gaddis, Judy Walters, and Godfrey Muganda

Topics 14.1 Introduction to Recursion 14.2 The Recursive Factorial Function 14.3 The Recursive gcd Function 14.4 Solving Recursively Defined Problems 14.5 A Recursive Binary Search Function 14.6 The QuickSort Algorithm 14.7 The Towers of Hanoi 14.8 Exhaustive and Enumeration Algorithms 14.9 Recursion Versus Iteration

14.1 Introduction to Recursion A recursive function is a function that calls itself. Recursive functions can be useful in solving problems that can be broken down into smaller or simpler subproblems of the same type. A base case should eventually be reached, at which time the breaking down (recursion) will stop.

Recursive Functions Consider a function for solving the count-down problem from some number num down to 0: The base case is when num is already 0: the problem is solved and we “blast off!” If num is greater than 0, we count off num and then recursively count down from num-1

Recursive Functions A recursive function for counting down to 0: void countDown(int num) { if (num == 0) cout << "Blastoff!"; else cout << num << ". . ."; countDown(num-1); // recursive } // call }

What Happens When Called? If a program contains a line like countDown(2); countDown(2) generates the output 2..., then it calls countDown(1) countDown(1) generates the output 1..., then it calls countDown(0) countDown(0) generates the output Blastoff!, then returns to countDown(1) countDown(1) returns to countDown(2) countDown(2)returns to the calling function See pr14-01.cpp, pr14-02.cpp

What Happens When Called? first call to countDown num is 2 OUTPUT: 2... countDown(1); second call to countDown num is 1 1... countDown(0); third call to countDown num is 0 Blastoff! // no // recursive // call

Stopping the Recursion A recursive function should include a test for the base cases In the sample program, the test is: if (num == 0)

Stopping the Recursion void countDown(int num) { if (num == 0) // test cout << "Blastoff!"; else cout << num << "...\n"; countDown(num-1); // recursive } // call }

Stopping the Recursion With each recursive call, the parameter controlling the recursion should move closer to the base case Eventually, the parameter reaches the base case and the chain of recursive calls terminates

Stopping the Recursion void countDown(int num) { if (num == 0) // base case cout << "Blastoff!"; else { cout << num << "...\n"; countDown(num-1); } Value passed to recursive call is closer to base case of num = 0.

What Happens When Called? Each time a recursive function is called, a new copy of the function runs, with new instances of parameters and local variables being created As each copy finishes executing, it returns to the copy of the function that called it When the initial copy finishes executing, it returns to the part of the program that made the initial call to the function See pr14-03.cpp

Types of Recursion Direct recursion Indirect recursion a function calls itself Indirect recursion function A calls function B, and function B calls function A. Or, function A calls function B, which calls …, which then calls function A

14.2 The Recursive Factorial Function The factorial of a nonnegative integer n is the product of all positive integers less than or equal to n The factorial of n is denoted by n! The factorial of 0 is 1 0 ! = 1 n ! = n x (n-1) x … x 2 x 1 if n > 0

Recursive Factorial Function Factorial of n can be expressed in terms of the factorial of n-1 0 ! = 1 n ! = n x (n-1) ! Recursive function int factorial(int n) { if (n == 0) return 1; // base else return n *factorial(n-1); } See pr14-04.cpp

14.3 The Recursive gcd Function Greatest common divisor (gcd) of two integers x and y is the largest number that divides both x and y with no remainder. The Greek mathematician Euclid discovered that If y divides x, then gcd(x, y) is just y Otherwise, the gcd(x, y) is the gcd of y and the remainder of dividing x by y

The Recursive gcd Function int gcd(int x, int y) { if (x % y == 0) //base case return y; else return gcd(y, x % y); } See pr14-05.cpp

14.4 Solving Recursively Defined Problems The natural definition of some problems leads to a recursive solution Example: Fibonacci numbers: 0, 1, 1, 2, 3, 5, 8, 13, 21, ... After the initial 0 and 1, each term is the sum of the two preceding terms Recursive calculation of the nth Fibonacci number: fib(n) = fib(n – 1) + fib(n – 2); Base cases: n == 0, n == 1

Recursive Fibonacci Function Note: Very inefficient method Why? int fib(int n) { if (n <= 0) // base case return 0; else if (n == 1) // base case return 1; else return fib(n – 1) + fib(n – 2); } See pr14-06.cpp

14.5 A Recursive Binary Search Function Assume an array a that is sorted in ascending order, and an item X to search for We want to write a function that searches for X within the array a, returning the index of X if it is found, and returning -1 if X is not in the array

Recursive Binary Search A recursive strategy for searching a portion of the array from index lo to index hi is to set m to the index of the middle element of the array: m lo hi

Recursive Binary Search If a[m] == X, we found X, so return m If a[m] > X, recursively search a[lo..m-1] If a[m] < X, recursively search a[m+1..hi] m lo hi

Recursive Binary Search int bSearch(const int a[],int lo, int hi,int X) { int m = (lo + hi) /2; if(lo > hi) return -1; // base if(a[m] == X) return m; // base if(a[m] > X) return bsearch(a,lo,m-1,X); else return bsearch(a,m+1,hi,X); } See pr14-07.cpp

Add digits of int recursively int SumDigits(int val){ if( val==0) return 0; else{ // get least significant digit d = val % 10; return (d+SumDigits(val/10)); }

SumDigits example 4235 = 5 + SumDigits(423) 3 + SumDigits(42) 2 + SumDigits (4) 4 + SumDigits(0) 0 SumDigits(4235)= 5 +( 3 + ( 2 + (4 + (0))))

String Class Review (in STL) http://www. cplusplus Let s= “PROGRAM” Length of string s.length() is 7 Last char in string s.back() is ‘M’ Substring s.substr( start_pos, length) s.substr(2,3) is “OGR” s.substr(4) is “RAM” until end

Reverse a string Note: Rev(CABLE) = “E”+Rev(CABL) string Rev(string s){ if (s=“”) return “”; //<=Base case int L=s.length(); return( s.back() + Rev(s.substr(0,L-1)); } concat everything BUT last char

Count char in string example s= “hello” int Count(string s, char c){ if (s.length()==0) return 0;//base case if( s[0]==c) return(1 + Count( s.substr(1),c); else return(0 + Count( s.substr(1),c); } // position 1 until end of string ie this is 1 char shorter // Note : if pos == length of string then returns “”

Print all possible suffixes of string void PrintSuffix(string s){ if (s.length()==0) return; // we are done cout<<s<<endl; PrintSuffix(s.substr(1)); } // rest of string after the first.

14.8 Exhaustive and Enumeration Algorithms Enumeration algorithm: generate all possible combinations Example: all possible ways to make change for a certain amount of money Exhaustive algorithm: search a set of combinations to find an optimal one Example: change for a certain amount of money that uses the fewest coins See pr14-10.cpp

14.9 Recursion vs. Iteration Benefits (+), disadvantages(-) for recursion: Natural formulation of solution to certain problems Results in shorter, simpler functions May not execute very efficiently Benefits (+), disadvantages(-) for iteration: Executes more efficiently than recursion May not be as natural a method of solution as recursion for some problems

Some Thoughts Recursion is a very powerful method that takes some getting use to. You need to write a lot of problems to get comfortable. I did. Its normally easy to understand recursive algorithms that you read. Writing them from scratch is what needs work.

Remember the following! Don’t practice until you get it right. Practice until you can’t get it wrong!

Chapter 14: Recursion Starting Out with C++ Early Objects Ninth Edition by Tony Gaddis, Judy Walters, and Godfrey Muganda