Recursion Chapter 12. 2 12.1 Nature of Recursion t Problems that lend themselves to a recursive solution have the following characteristics: –One or more.

Slides:



Advertisements
Similar presentations
Towers of Hanoi Move n (4) disks from pole A to pole C such that a disk is never put on a smaller disk A BC ABC.
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.
Programming with 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.
Chapter 10 Recursion Dr. Jiung-yao Huang Dept. Comm. Eng. Nat. Chung Cheng Univ. TA: 鄭筱親 陳昱豪.
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.
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.
CS212: DATASTRUCTURES Lecture 3: Recursion 1. Lecture Contents 2  The Concept of Recursion  Why recursion?  Factorial – A case study  Content of a.
1 Chapter 18-1 Recursion Dale/Weems. 2 Chapter 18 Topics l Meaning of Recursion l Base Case and General Case in Recursive Function Definitions l Writing.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 19: Recursion.
Modular Programming Chapter Value and Reference Parameters t Function declaration: void computesumave(float num1, float num2, float& sum, float&
Recursion Chapter 7 Copyright ©2012 by Pearson Education, Inc. All rights reserved.
 2003 Prentice Hall, Inc. All rights reserved. 1 Functions and Recursion Outline Function Templates Recursion Example Using Recursion: The Fibonacci Series.
Chapter 2 Recursion: The Mirrors CS Data Structures Mehmet H Gunes Modified from authors’ slides.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 12: Recursion Problem Solving, Abstraction, and Design using C++
Recursion.
Modular Programming Chapter Value and Reference Parameters computeSumAve (x, y, sum, mean) ACTUALFORMAL xnum1(input) ynum2(input) sumsum(output)
© 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.
Programming Principles II Lecture Notes 5 Recursion Andreas Savva.
1 Lecture 14 Chapter 18 - Recursion. 2 Chapter 18 Topics l Meaning of Recursion l Base Case and General Case in Recursive Function Definitions l Writing.
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.
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 7.Algorithm Efficiency What to measure? Space utilization: amount of memory required  Time efficiency: amount of time required to process the data Depends.
Recursion. Circular Definition Circular definition Circular definition Dialectic materialism is materialism that is dialectic. Dialectic materialism is.
CS212: DATASTRUCTURES Lecture 3: Recursion 1. Lecture Contents 2  The Concept of Recursion  Why recursion?  Factorial – A case study  Content of a.
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.
1 7.Algorithm Efficiency What to measure? Space utilization: amount of memory required  Time efficiency: amount of time required to process the data.
Current Assignments Homework 3 is due tonight. Iteration and basic functions. Exam 1 on Monday.
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.
© Janice Regan, CMPT 128, February CMPT 128: Introduction to Computing Science for Engineering Students Recursion.
Recursion. Circular Definition (not useful) E.g., E.g., Projenitor: one who produces an offspring Projenitor: one who produces an offspring Offspring:
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.
Starting Out with C++, 3 rd Edition Chapter 19 Recursion.
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! =
chap10 Chapter 10 Recursion chap10 2 Recursive Function recursive function The recursive function is a kind of function that calls.
Program Development and Design Using C++, Third Edition
1 7.Algorithm Efficiency These factors vary from one machine/compiler (platform) to another  Count the number of times instructions are executed So, measure.
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 Powerful Tool
Chapter 19: Recursion.
COMP 51 Week Fourteen Recursion.
Recursion CENG 707.
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.
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
7.2 Recursive Definitions of Mathematical Formulas
Announcements Final Exam on August 17th Wednesday at 16:00.
Announcements Final Exam on August 19th Saturday at 16:00.
Recursion Chapter 18.
Chapter 18 Recursion.
Chapter 3 :Recursion © 2011 Pearson Addison-Wesley. All rights reserved.
7.2 Recursive Definitions of Mathematical Formulas
Presentation transcript:

Recursion Chapter 12

Nature of Recursion t 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 –Otherwise, use reduced cases of the problem that are closer to a stopping case –Eventually the problem can be reduced to stopping cases only. Easy to solve

3 Nature of Recursion Splitting a problem into smaller problems Size n Problem Size n-1 Problem Size n-2 Problem Size 1 problem Size 1 problem Size 1 problem

4 Power by Multiplication t Raise 6 to the power of 3 –Raise 6 to the power of 22 –Multiply the result by 6 t Raise 6 to the power of 2 –Raise 6 to the power of 1 –Multiply the result by 6 t Multiplying 6 * 6 * 6

5 Power.cpp // 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 > 0. // Post:Returns m raised to power n. int power (int m, int n) { if (n <= 1) return m; else return m + power (m, n - 1); }

Tracing Recursive Functions t Hand tracing we see how algorithm works t Very useful in recursion t Previous Multiply example trace t “Activation Frame” corresponds to a function call t Darker shading shows the depth of recursion

7 Trace of Power

8 Recursive Function with No Return Value t If statement with some stopping condition –n <= 1; t When TRUE stopping case is reached –recursive step is finished –falls back to previous calls (if any) –trace of reverse t ReverseTest.cpp

9 ReverseTest.cpp #include using namespace std; void reverse(); int main () { reverse(); cout << endl; return 0; }

10 ReverseTest.cpp void reverse() { char next; cout << "Next character or * to stop: "; cin >> next; if (next != ‘*’) { reverse(); cout << next; }

11 Reverse Trace

12 Argument and Local Variable Stacks t How does C++ keep track of n and next ? t Uses a data structure called a stack t Think of a stack of trays in a cafeteria t Each time a function is called it is pushed onto the stack t Only top values are used when needed (popping) t Example of calls to reverse

13 Recursive String t After 1st call to reverse nnext 3 ?top –c is read into next just prior to 2nd call nnext 3 ctop

14 Recursive String t After 2nd call to reverse nnext 2 ?top 3 c –letter a is read into next just prior to 3rd call nnext 2 atop 3 c

15 Recursive String t After 3rd call to reverse nnext 1 ?top 2 a 3 c –letter t is read into next printed due to stop case nnext 1 ttop 2 a 3 c

16 Recursive String t After 1st return nnext 2 atop 3 c t After 2nd return nnext 3 c t After 3rd return (final) ?

Recursive Mathematical Functions t Many mathematical functions are defined recursively –factorial n! of a number –0! = 1 –n! = n * *n-1)! for n > 0 –So 4! = 4 * 3 * 2 * 1 or 24 t Look at a block of recursive math function example source code files

18 Factorial.cpp // FILE: Factorial.cpp // RECURSIVE FACTORIAL FUNCTION // COMPUTES N! int factorial (int n) { if (n <= 0) return 1; else return n * factorial (n-1); }

19 Factorial Trace

20 FactorialI.cpp // FILE: FactorialI.cpp // ITERATIVE FACTORIAL FUNCTION // COMPUTES N! int factorialI (int n) { int factorial; factorial = 1; for (int i = 2; i <= n; i++) factorial *= i; return factorial; }

21 Fibonacci.cpp // FILE: Fibonacci.cpp // RECURSIVE FIBONACCI NUMBER FUNCTION int fibonacci (int n) // Pre: n is defined and n > 0. // Post: None // Returns: The nth Fibonacci number. { if (n <= 2) return 1; else return fibonacci (n - 2) + fibonacci (n - 1); }

22 GCDTest.cpp // FILE: gcdTest.cpp // Program and recursive function to find // greatest common divisor #include using namespace std; // Function prototype int gcd(int, int);

23 GCDTest.cpp int main() { int m, n; // the two input items cout << "Enter two positive integers: "; cin >> m >> n; cout << endl; cout << "Their greatest common divisor is " << gcd(m, n) << endl; return 0; }

24 GCDTest.cpp // Finds the greatest common divisor of two // integers // Pre: m and n are defined and both are > 0. // Post: None // Returns: The greatest common divisor of m and // n. int gcd(int m, int n) { if (m < n) return gcd(n, m);

25 GCDTest.cpp else if (m % n == 0) return n; else return gcd(n, m % n); // recursive step }

26 GCDTest.cpp Program Output Enter two positive integers separated by a space: Their greatest common divisor is 12

Recursive Functions with Array Arguments // File: findSumTest.cpp // Program and recursive function to sum an // array's elements #include using namespace std; // Function prototype int findSum(int[], int); int binSearch(int[], int, int, int);

28 FindSumTest.cpp int main() { const int SIZE = 10; int x[SIZE]; int sum1; int sum2; // Fill array x for (int i = 0; i < SIZE; i++) x[i] = i + 1;

29 FindSumTest.cpp // 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; cout << binSearch(x, 10, 10, SIZE-1) << endl; return 0; }

30 FindSumTest.cpp // Finds the sum of integers in an n-element // array int findSum(int x[], int n) { if (n == 1) return x[0]; else return x[n-1] + findSum(x, n-1); }

31 FindSumTest.cpp // Searches for target in elements first through // last of array // Precondition : The elements of table are // sorted & first and last are defined. // Postcondition: If target is in the array, // return its position; otherwise, returns -1. int binSearch (int table[], int target, int first, int last) { int middle;

32 FindSumTest.cpp middle = (first + last) / 2; if (first > last) return -1; else if (target == table[middle]) return middle; else if (target < table[middle]) return binSearch(table, target, first, middle-1); else return binSearch(table, target, middle+1, last); }

Problem Solving with Recursion t Case Study: The Towers of Hanoi t 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 t Problem 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.

34 Towers of Hanoi t Program Design –If n is 1 move disk 1 from fromTower to toTower –else move n-1 disks from fromTower to aux tower using the toTower move disk n from the fromTower to the toTower move n-1 disks from aux tower to the toTower using fromTower

35 Towers of Hanoi t Program Implementation –Towers.cpp t Program Verification & Test –towers (‘A’, ’C’, ‘B’, 3); t Towers trace

36 Tower.cpp // File: tower.cpp // Recursive tower of hanoi function #include using namespace std; void tower(char, char, char, int); int main() { int numDisks; // input - number of disks

37 Tower.cpp cout << "How many disks: "; cin >> numDisks; tower('A', 'C', 'B', numDisks); return 0; } // Recursive function to "move" n disks from // fromTower to toTower using auxTower // Pre: The fromTower, toTower, auxTower, and // n are defined. // Post: Displays the required moves.

38 Tower.cpp 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 {

39 Tower.cpp 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

40 Towers Trace

41 TowerTest.cpp Program Output 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

Common Programming Errors t Stopping conditions t Missing return statements t Optimizations –recursion of arrays use large amounts of memory –use care when tracing your solutions