© Janice Regan, CMPT 128, February. 2007 0 CMPT 128: Introduction to Computing Science for Engineering Students Recursion.

Slides:



Advertisements
Similar presentations
Basics of Recursion Programming with Recursion
Advertisements

Copyright © 2002 Pearson Education, Inc. Slide 1.
Chapter 13 Recursion. Copyright © 2006 Pearson Addison-Wesley. All rights reserved Learning Objectives Recursive void Functions Tracing recursive.
Recursion in Python. Recursion Problems in every area of life can be defined recursively, that is, they can be described in terms of themselves. An English.
Recursive methods. Recursion A recursive method is a method that contains a call to itself Often used as an alternative to iteration when iteration is.
© Janice Regan, CMPT 102, Sept CMPT 102 Introduction to Scientific Computer Programming Recursion.
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.
Slides prepared by Rose Williams, Binghamton University Chapter 11 Recursion.
Recursion. Binary search example postponed to end of lecture.
Slides prepared by Rose Williams, Binghamton University Chapter 11 Recursion.
Recursion. Objectives At the conclusion of this lesson, students should be able to Explain what recursion is Design and write functions that use recursion.
Slides prepared by Rose Williams, Binghamton University Chapter 11 Recursion.
Recursion.
Chapter 11 Recursion Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 3 - Functions Outline 3.12Recursion 3.13Example Using Recursion: The Fibonacci Series 3.14Recursion.
Copyright © 2003 Pearson Education, Inc. Slide 1.
CHAPTER 10 Recursion. 2 Recursive Thinking Recursion is a programming technique in which a method can call itself to solve a problem A recursive definition.
CS212: DATASTRUCTURES Lecture 3: Recursion 1. Lecture Contents 2  The Concept of Recursion  Why recursion?  Factorial – A case study  Content of a.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 19: Recursion.
Recursion Chapter 7 Copyright ©2012 by Pearson Education, Inc. All rights reserved.
Recursion Chapter Nature of Recursion t Problems that lend themselves to a recursive solution have the following characteristics: –One or more.
Recursion, Complexity, and Searching and Sorting By Andrew Zeng.
A Computer Science Tapestry 1 Recursion (Tapestry 10.1, 10.3) l Recursion is an indispensable technique in a programming language ä Allows many complex.
Chapter 13 Recursion. Topics Simple Recursion Recursion with a Return Value Recursion with Two Base Cases Binary Search Revisited Animation Using Recursion.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
Comp 249 Programming Methodology Chapter 10 – Recursion Prof. Aiman Hanna Department of Computer Science & Software Engineering Concordia University, Montreal,
Chapter 11 Recursion Slides prepared by Rose Williams, Binghamton University Copyright © 2008 Pearson Addison-Wesley. All rights reserved.
Recursion, Complexity, and Sorting By Andrew Zeng.
Chapter 12 Recursion, Complexity, and Searching and Sorting
Lecturer: Dr. AJ Bieszczad Chapter 11 COMP 150: Introduction to Object-Oriented Programming 11-1 l Basics of Recursion l Programming with Recursion Recursion.
Slides prepared by Rose Williams, Binghamton University ICS201 Lecture 19 : Recursion King Fahd University of Petroleum & Minerals College of Computer.
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.
CS212: DATASTRUCTURES Lecture 3: Recursion 1. Lecture Contents 2  The Concept of Recursion  Why recursion?  Factorial – A case study  Content of a.
Chapter 13 Recursion. Learning Objectives Recursive void Functions – Tracing recursive calls – Infinite recursion, overflows Recursive Functions that.
Chapter 13 Recursion. Copyright © 2005 Pearson Addison-Wesley. All rights reserved. Slide 2 Overview Recursive Functions for Tasks(13.1) Recursive Functions.
Copyright © 2012 Pearson Addison-Wesley. All rights reserved. Chapter 14 Recursion.
CSIS 123A Lecture 9 Recursion Glenn Stevenson CSIS 113A MSJC.
Edited by Malak Abdullah Jordan University of Science and Technology Data Structures Using C++ 2E Chapter 6 Recursion.
Data Structures R e c u r s i o n. Recursive Thinking Recursion is a problem-solving approach that can be used to generate simple solutions to certain.
Java Programming: Guided Learning with Early Objects Chapter 11 Recursion.
Recursion Unit 15. Recursion: Recursion is defined as the process of a subprogram calling itself as part of the solution to a problem. It is a problem.
Chapter 11Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 11 l Basics of Recursion l Programming with Recursion Recursion.
Chapter 11 Recursion Slides prepared by Rose Williams, Binghamton University Copyright © 2008 Pearson Addison-Wesley. All rights reserved.
Slide 1 Chapter 13 Recursion Written by Walter Savitch, UCSD Modified by Tsung Lee, NSYSU EE.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 16: Recursion.
Recursion A function is said to be recursive if it calls itself, either directly or indirectly. void repeat( int n ) { cout
Chapter 111 Recursion Chapter Objectives become familiar with the idea of recursion learn to use recursion as a programming tool become familiar.
JAVA: An Introduction to Problem Solving & Programming, 7 th Ed. By Walter Savitch ISBN © 2015 Pearson Education, Inc., Upper Saddle River,
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 14 Recursion.
Recursion. Objectives At the conclusion of this lesson, students should be able to Explain what recursion is Design and write functions that use 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! =
Recursion Chapter 7 Copyright ©2012 by Pearson Education, Inc. All rights reserved.
Function Recursion to understand recursion you must understand recursion.
Chapter 13 Recursion Copyright © 2016 Pearson, Inc. All rights reserved.
Recursion Version 1.0.
to understand recursion you must understand recursion
Recursion DRILL: Please take out your notes on Recursion
Chapter 11 Recursion Slides prepared by Rose Williams, Binghamton University Kenrick Mock, University of Alaska Anchorage Copyright © 2016 Pearson Inc.
Recursive Thinking Chapter 9 introduces the technique of recursive programming. As you have seen, recursive programming involves spotting smaller occurrences.
CIS Principles of Programming
Chapter 14 Recursion. Chapter 14 Recursion Overview 14.1 Recursive Functions for Tasks 14.2 Recursive Functions for Values 14.3 Thinking Recursively.
to understand recursion you must understand recursion
Recursive Thinking Chapter 9 introduces the technique of recursive programming. As you have seen, recursive programming involves spotting smaller occurrences.
Applied Algorithms (Lecture 17) Recursion Fall-23
Recursion This slide set was compiled from the Absolute Java textbook slides (Walter Savitch) and the instructor’s class materials.
Basics of Recursion Programming with Recursion
Recursion Chapter 11.
Comp 249 Programming Methodology
Chapter 13 Recursion Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
Presentation transcript:

© Janice Regan, CMPT 128, February CMPT 128: Introduction to Computing Science for Engineering Students Recursion

© Janice Regan, CMPT 128, Introduction to Recursion  Recursion:  A function that calls itself is said to be a recursive function  A function that calls itself results in direct recursion  If function A calls function B, and in turn function B calls function A this results in indirect recursion  C++, like most high-level languages, allows recursion  Recursion can result in elegant easy to understand and develop code (‘efficient’ development and maintenance)  Recursion may be less ‘efficient’ to execute than an equivalent iterative solution,

© Janice Regan, CMPT 128, Recursive void Functions  Recursion is based on the design technique know as ‘divide and conquer’  Divide: break the task into smaller parts  Conquer: solve a large and complex problem efficiently  When solving a problem recursively  Divide: each smaller part of the task is the same as the whole task The same algorithm or series of steps is used for the whole problem and for each smaller task the problem is divided into

© Janice Regan, CMPT 128, Example: quick sort  Consider large task: sort a large array into descending order  Choose pivot from ‘middle’ of array, Switch the pivot and first element in array  Sort the array into two parts, one with all numbers larger than the pivot, one with all numbers smaller than the pivot  Move the pivot back between the two parts  Subtasks must be smaller versions of original task  Subtask 1: repeat the main task on the part of the array with elements larger than the pivot  Subtask 2: repeat the main task on the part of the array with elements smaller than the pivot.  Quick sort is a method of the type that is well suited to be solved by recursion

© Janice Regan, CMPT 128, Recursive void Function: a simple example  Task: calculate the sum of the squares of all integers from 1 to j, for all integers j from 1 to n. Display sums of integers vertically, one line for each j, beginning with j=1  Example call: sumSqIntegers(4); Produces output:

© Janice Regan, CMPT 128, Sums of squares: Recursive Definition  Break problem into two cases  Base case: if n=1  Simply write number n to screen (1*1=1)  Do not call the function again  Return to the calling function (previous recursive call)  Recursive case: if n>1, two subtasks:  Calculate and print all sums for j=1,..,n-1  Calculate and print the sum for j=n  Return to the calling function

© Janice Regan, CMPT 128, Sums of squares: Recursive Definition  Example: argument 4:  1 st subtask calculates the sums for each j j=1,…,3 and prints them one per line 1, 5, 14 Call the function sumSqIntegers for j-1  2 nd subtask calculates the sum for j=4 and prints it on a new line, 30  Return to the calling program

© Janice Regan, CMPT 128, sumSqIntegers: Function Definition void sumSqIntegers(int maxInteger, int& value) { if (maxInteger == 1) { cout << maxInteger << endl; //Base case value = maxInteger; } else { sumSqIntegers(maxInteger-1, value); value += maxInteger * maxInteger; //Recursive case cout << value << endl;}

© Janice Regan, CMPT 128, Sums of squares: Trace (1)  Example call: sumSqIntegers(4,value); //1 st call sumSqIntegers(3,value); //2 nd call sumSqIntegers(2,value); //3 rd call sumSqIntegers(1,value); //4 th call cout << 1 << endl; //4 th call cout << 2*2 + 1 << endl; //3 rd call cout << 3*3 + 5 << endl; //2 nd call cout << 4*4 +14 << endl; //1 st call

© Janice Regan, CMPT 128, Sums of squares: Trace (2)  During 1 st call n=4, and the function is called for n=3 (recursive case)  During 2 nd call n=3, and the function is called for n=2 (recursive case)  During 3 rd call n=2, and the function is called for n=1 (recursive case)  During 4 th call n=1, 1is printed to the screen and the cursor moves to the next line (stopping case) then returns to 3 rd case  During the remainder of the 3 rd call n=2, 5 is printed to the screen and the cursor moves to the next line (completes recursive case) then returns to 2 nd case  During the remainder of the 2 nd call n=3, 14 is printed to the screen and the cursor moves to the next line (completes recursive case) then returns to 1 st case  During the remainder of the 1 st call n=4, 30 is printed to the screen and the cursor moves to the next line (completes recursive case) then returns to calling program

© Janice Regan, CMPT 128, Sums of squares: Trace (3) void sumSqIntegers(int maxInteger, int& value) { if (maxInteger == 1) { //Base case cout << maxInteger << endl; value = maxInteger; } else { //Recursive case sumSqIntegers(maxInteger-1, value); value += maxInteger * maxInteger; cout << value << endl;} 3 rd call: sumSqIntegers(1, value) 4 th call: Print 1, value=1 Calling function: sumSqIntegers(4, value) 1 st call: sumSqIntegers(3, value) 2 nd call: sumSqIntegers(2, value)

© Janice Regan, CMPT 128, Sums of squares: Trace (4) Calling function: sumSqIntegers(4, value) 1 st call: sumSqIntegers(3, value) 2 nd call: sumSqIntegers(2, value) 3 rd call: determine value value = 1+2*2 Print 5 void sumSqIntegers(int maxInteger, int& value) { if (maxInteger == 1) { //Base case cout << maxInteger << endl; value = maxInteger; } else { //Recursive case sumSqIntegers(maxInteger-1, value); value += maxInteger * maxInteger; cout << value << endl;}

© Janice Regan, CMPT 128, Sums of squares: Trace (5) Calling function: sumSqIntegers(4, value) 1 st call: sumSqIntegers(3, value) void sumSqIntegers(int maxInteger, int& value) { if (maxInteger == 1) { //Base case cout << maxInteger << endl; value = maxInteger; } else { //Recursive case sumSqIntegers(maxInteger-1, value); value += maxInteger * maxInteger; cout << value << endl;} 2 nd call: determine value value = 5 + 3*3 Print 14

© Janice Regan, CMPT 128, Sums of squares: Trace (6) Calling function: sumSqIntegers(4, value) void sumSqIntegers(int maxInteger, int& value) { if (maxInteger == 1) { //Base case cout << maxInteger << endl; value = maxInteger; } else { //Recursive case sumSqIntegers(maxInteger-1, value); value += maxInteger * maxInteger; cout << value << endl;} 1 st call: determine value value = 14+4*4 Print 30

© Janice Regan, CMPT 128, Infinite Recursion  Base case MUST eventually be entered  If there is no base case OR  If the base case is never reached  Then recursion continues for ever (or at least until memory for new function frames is exhausted)  In our example (sumSqIntegers):  Base case happened when we reached 1, the sum of the squares of integers 1,..,1 is 1  That’s when recursion stopped and we began returning up through the stack of recursive frames

© Janice Regan, CMPT 128, Infinite Recursion: Example  Consider alternate function definition: void altSumSqIntegers(int maxInteger, int& value) { altsumSqIntegers(maxInteger-1, value); value += maxInteger * maxInteger; cout << value << endl; }  Seems logical on the surface but there is no stopping case so recursion never stops

© Janice Regan, CMPT 128, Recursion: Review  A recursive function must have:  One or more recursive cases where the function accomplishes it’s task by: Making one or more recursive calls to solve smaller versions of original task  One or more base cases or stopping cases where the function accomplishes it’s task by simple calculation without recursive call

© Janice Regan, CMPT 128, Stacks for Recursion  A stack  Specialized memory structure  Like stack of paper Place each new page (frame) on top When you finish with one page (frame) then take the page (frame) from the top of the stack and continue  Called "last-in/first-out“ (LIFO) memory structure  Recursion uses stacks  Each recursive call placed on stack  When one completes, last call is removed from stack

© Janice Regan, CMPT 128, Stack Overflow  Size of stack limited  Memory is finite  Long chain of recursive calls continually adds to stack  All are added before base case causes removals  If stack attempts to grow beyond limit:  Stack overflow error  Infinite recursion always causes this

© Janice Regan, CMPT 128, Why Use Recursion  Recursion is not always the ‘best solution’  Some languages do not allow recursion  Any task accomplished with recursion can also be done using iteration  Recursive:  Recursion can result in elegant easy to understand and develop code (‘efficient’ development and maintenance)  Recursion may be less ‘efficient’ to execute than an equivalent iterative solution (may run slower)

© Janice Regan, CMPT 128, Recursive Functions can have any type  Recursion not limited to void functions  Can return value of any type  Same approach as for our original example  Let’s recast that original example so that the recursive function has type int rather than type void

© Janice Regan, CMPT 128, sumSqIntegers: Function Definition int sumSqIntegers(int maxInteger) { int value; if (maxInteger == 1) { cout << maxInteger << endl; //Base case return(maxInteger); } else { sumSqIntegers(maxInteger-1); value += maxInteger * maxInteger; //Recursive case cout << value << endl; return(value);}

© Janice Regan, CMPT 128, Sums of squares: Trace (1)  Example call: sumSqIntegers(4); //1 st call sumSqIntegers(3); //2 nd call sumSqIntegers(2); //3 rd call sumSqIntegers(1); //4 th call cout << 1 << endl; //4 th call cout << 2*2 + 1 << endl; //3 rd call cout << 3*3 + 5 << endl; //2 nd call cout << 4*4 +14 << endl; //1 st call

© Janice Regan, CMPT 128, Return a Value Recursion Example: Powers  Recall predefined function pow(): result = pow(2.0,3.0);  Returns 2 raised to power 3 (8.0)  Takes two double arguments  Returns double value  Let’s write recursively  For simple example

© Janice Regan, CMPT 128, Function Definition for power() int power(int x, int n) { if (n 0) { return (power(x, n-1)*x); } else { return (1); } }

© Janice Regan, CMPT 128, Calling Function power()  Larger example: power(2,3);  power(2,2)*2  power(2,1)*2  power(2,0)*2  1  Reaches base case  Recursion stops  Values "returned back" up stack

© Janice Regan, CMPT 128, Recursive Design Techniques  Start simple  Make sure the problem can be broken into parts that are copies of each other and the ‘whole’ problem  Define your recursive cases  Do the recursive cases return or produce the correct results  Define your stopping case or cases  When will the series of recursive calls end  Do the stopping cases return or produce the correct results  Make sure that you stop your recursive case and enter the stopping cases when conditions are correct

© Janice Regan, CMPT 128, Recursive design: power  Consider power() again  Can the problem be broken down into smaller parts:  x n = x i *x k where n=i+k  this problem can be broken down into parts that are equivalent to the ‘whole’ problem  Design the recursive case  power(x, n) returns: power(x, n – 1) * x  Is this correct? x n = x n-1 *x so yes  Design the stopping case  x 0 =1, x 1 =x When do we stop?  When n=0 we know the answer regardless of the value of x  So out stopping case is n=0, x 0 =1

© Janice Regan, CMPT 128, Recursive Design Check: power()  Can infinite recursion happen with the power() function we have designed  2 nd argument decreases by 1 each call  Eventually we will reach the base case of n=0  Does the stopping case return the correct value:  n=0 is base case which implies power(x,0)  power(x,0) returns 1, which is correct for x 0  Does the recursive case return the correct value:  For n>1, power(x,n) returns power(x,n-1)*x  x n = x n-1 *x so this is correct

© Janice Regan, CMPT 128, Another recursive example  Now lets return to our discussion of quick sort and see the application of recursion to that algorithm