Slides prepared by Rose Williams, Binghamton University Chapter 11 Recursion.

Slides:



Advertisements
Similar presentations
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.
Advertisements

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.
Computer Science II Recursion Professor: Evan Korth New York University.
Chapter 10 Recursion Instructor: alkar/demirer. Copyright ©2004 Pearson Addison-Wesley. All rights reserved.10-2 Recursive Function recursive functionThe.
Slides prepared by Rose Williams, Binghamton University Chapter 11 Recursion.
Recursion. Binary search example postponed to end of lecture.
Unit 181 Recursion Definition Recursive Methods Example 1 How does Recursion work? Example 2 Problems with Recursion Infinite Recursion Exercises.
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.
Chapter 10 Recursion. Copyright © 2005 Pearson Addison-Wesley. All rights reserved Chapter Objectives Explain the underlying concepts of recursion.
Recursion.
Slides prepared by Rose Williams, Binghamton University Chapter 11 Recursion.
Chapter 11 Recursion Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
Copyright © 2003 Pearson Education, Inc. Slide 1.
Slides prepared by Rose Williams, Binghamton University Chapter 11 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.
Slides prepared by Rose Williams, Binghamton University Chapter 11 Recursion.
Recursion Chapter 7. Chapter 7: Recursion2 Chapter Objectives To understand how to think recursively To learn how to trace a recursive method To learn.
19-Aug-15 Simple Recursive Algorithms. 2 A short list of categories Algorithm types we will consider include: Simple recursive algorithms Backtracking.
CSC1016 Welcome (again!) Get course notes handout (and read them) The question of whether computers can think is like the question of whether submarines.
Recursion Chapter 7 Copyright ©2012 by Pearson Education, Inc. All rights reserved.
20-1 Computing Fundamentals with C++ Object-Oriented Programming and Design, 2nd Edition Rick Mercer Franklin, Beedle & Associates, 1999 ISBN
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 12: Recursion Problem Solving, Abstraction, and Design using C++
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 Chapter 7. Chapter Objectives  To understand how to think recursively  To learn how to trace a recursive method  To learn how to write recursive.
Recursion.  A recursive function contains a call to itself Example: the factorial n!=n*(n-1)! for n>1 n!=1 for n=1 int factorial (int n) { if (n == 0)
M180: Data Structures & Algorithms in Java
Chapter 12 Recursion, Complexity, and Searching and Sorting
Slides prepared by Rose Williams, Binghamton University ICS201 Lecture 19 : Recursion King Fahd University of Petroleum & Minerals College of Computer.
1 CS 177 Week 16 Recitation Recursion. 2 Objective To understand and be able to program recursively by breaking down a problem into sub problems and joining.
Chapter 13 Recursion. Learning Objectives Recursive void Functions – Tracing recursive calls – Infinite recursion, overflows Recursive Functions that.
Chapter 4 Recursion. Copyright © 2004 Pearson Addison-Wesley. All rights reserved.1-2 Chapter Objectives Explain the underlying concepts of recursion.
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.
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.
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.
© 2011 Pearson Education, publishing as Addison-Wesley Chapter 8: Recursion Presentation slides for Java Software Solutions for AP* Computer Science 3rd.
1 Recursion Recursion is a powerful programming technique that provides elegant solutions to certain problems. Chapter 11 focuses on explaining the underlying.
© Janice Regan, CMPT 128, February CMPT 128: Introduction to Computing Science for Engineering Students Recursion.
CS162 - Topic #10 Lecture: Recursion –The Nature of Recursion –Tracing a Recursive Function –Work through Examples of Recursion Programming Project –Discuss.
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.
chap10 Chapter 10 Recursion chap10 2 Recursive Function recursive function The recursive function is a kind of function that calls.
CS 116 Object Oriented Programming II Lecture 13 Acknowledgement: Contains materials provided by George Koutsogiannakis and Matt Bauer.
Function Recursion to understand recursion you must understand recursion.
1 CSC 143 Recursion [Reading: Chapter 17]. 2 Recursion  A recursive definition is one which is defined in terms of itself.  Example:  Sum of the first.
Recursion Chapter 10 Carrano, Data Structures and Abstractions with Java, Second Edition, (c) 2007 Pearson Education, Inc. All rights reserved X.
Chapter 13 Recursion Copyright © 2016 Pearson, Inc. All rights reserved.
to understand recursion you must understand recursion
Chapter 10 Recursion Instructor: Yuksel / Demirer.
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.
Data Structures Recursion CIS265/506: Chapter 06 - Recursion.
Java Software Structures: John Lewis & Joseph Chase
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.
Recursion This slide set was compiled from the Absolute Java textbook slides (Walter Savitch) and the instructor’s class materials.
Comp 249 Programming Methodology
Chapter 13 Recursion Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
Presentation transcript:

Slides prepared by Rose Williams, Binghamton University Chapter 11 Recursion

© 2006 Pearson Addison-Wesley. All rights reserved11-2 A Closer Look at Recursion When the computer encounters a recursive call, it must temporarily suspend its execution of a method –It does this because it must know the result of the recursive call before it can proceed –It saves all the information it needs to continue the computation later on, when it returns from the recursive call Ultimately, this entire process terminates when one of the recursive calls does not depend upon recursion to return

© 2006 Pearson Addison-Wesley. All rights reserved11-3 General Form of a Recursive Method Definition The general outline of a successful recursive method definition is as follows: –One or more cases that include no recursive calls: base cases or stopping cases –One or more cases that include one or more recursive calls to the method being defined These recursive calls should solve "smaller" versions of the task performed by the method being defined They must come closer to the base case.

© 2006 Pearson Addison-Wesley. All rights reserved11-4 Pitfall: Infinite Recursion In the writeVertical example, the series of recursive calls eventually reached a call of the method that did not involve recursion (a stopping case) If, instead, every recursive call had produced another recursive call, then a call to that method would, in theory, run forever –This is called infinite recursion –In practice, such a method runs until the computer runs out of resources, and the program terminates abnormally

© 2006 Pearson Addison-Wesley. All rights reserved11-5 Pitfall: Infinite Recursion An alternative version of writeVertical –Note: No stopping case! public static void newWriteVertical(int n) { newWriteVertical(n/10); System.out.println(n%10); }

© 2006 Pearson Addison-Wesley. All rights reserved11-6 Pitfall: Infinite Recursion A program with this method will compile and run Calling newWriteVertical(12) causes that execution to stop to execute the recursive call newWriteVertical(12/10) –Which is equivalent to newWriteVertical(1) Calling newWriteVertical(1) causes that execution to stop to execute the recursive call newWriteVertical(1/10) –Which is equivalent to newWriteVertical(0)

© 2006 Pearson Addison-Wesley. All rights reserved11-7 Pitfall: Infinite Recursion Calling newWriteVertical(0) causes that execution to stop to execute the recursive call newWriteVertical(0/10) –Which is equivalent to newWriteVertical(0) –... And so on, forever! Since the definition of newWriteVertical has no stopping case, the process will proceed forever (or until the computer runs out of resources)

© 2006 Pearson Addison-Wesley. All rights reserved11-8 Stacks for Recursion To keep track of recursion (and other things), most computer systems use a stack –A stack is a very specialized kind of memory structure analogous to a stack of paper –As an analogy, there is also an inexhaustible supply of extra blank sheets of paper –Information is placed on the stack by writing on one of these sheets, and placing it on top of the stack (becoming the new top of the stack) –More information is placed on the stack by writing on another one of these sheets, placing it on top of the stack, and so on

© 2006 Pearson Addison-Wesley. All rights reserved11-9 Stacks for Recursion –To get information out of the stack, the top paper can be read, but only the top paper –To get more information, the top paper can be thrown away, and then the new top paper can be read, and so on Since the last sheet put on the stack is the first sheet taken off the stack, a stack is called a last-in/first-out memory structure (LIFO)

© 2006 Pearson Addison-Wesley. All rights reserved11-10 Stacks for Recursion To keep track of recursion, whenever a method is called, a new "sheet of paper" is taken –The method definition is copied onto this sheet, and the arguments are plugged in for the method parameters –The computer starts to execute the method body –When it encounters a recursive call, it stops the computation in order to make the recursive call –It writes information about the current method on the sheet of paper, and places it on the stack

© 2006 Pearson Addison-Wesley. All rights reserved11-11 Stacks for Recursion A new sheet of paper is used for the recursive call –The computer writes a second copy of the method, plugs in the arguments, and starts to execute its body –When this copy gets to a recursive call, its information is saved on the stack also, and a new sheet of paper is used for the new recursive call

© 2006 Pearson Addison-Wesley. All rights reserved11-12 Stacks for Recursion This process continues until some recursive call to the method completes its computation without producing any more recursive calls –Its sheet of paper is then discarded Then the computer goes to the top sheet of paper on the stack –This sheet contains the partially completed computation that is waiting for the recursive computation that just ended –Now it is possible to proceed with that suspended computation

© 2006 Pearson Addison-Wesley. All rights reserved11-13 Stacks for Recursion After the suspended computation ends, the computer discards its corresponding sheet of paper (the one on top) The suspended computation that is below it on the stack now becomes the computation on top of the stack This process continues until the computation on the bottom sheet is completed

© 2006 Pearson Addison-Wesley. All rights reserved11-14 Stacks for Recursion Depending on how many recursive calls are made, and how the method definition is written, the stack may grow and shrink in any fashion The stack of paper analogy has its counterpart in the computer –The contents of one of the sheets of paper is called a stack frame or activation record –The stack frames don't actually contain a complete copy of the method definition, but reference a single copy instead

© 2006 Pearson Addison-Wesley. All rights reserved11-15 Pitfall: Stack Overflow There is always some limit to the size of the stack –If there is a long chain in which a method makes a call to itself, and that call makes another recursive call,..., and so forth, there will be many suspended computations placed on the stack –If there are too many, then the stack will attempt to grow beyond its limit, resulting in an error condition known as a stack overflow A common cause of stack overflow is infinite recursion

© 2006 Pearson Addison-Wesley. All rights reserved11-16 Recursion Versus Iteration Recursion is not absolutely necessary –Any task that can be done using recursion can also be done in a nonrecursive manner –A nonrecursive version of a method is called an iterative version An iteratively written method will typically use loops of some sort in place of recursion A recursively written method can be simpler, but will usually run slower and use more storage than an equivalent iterative version

© 2006 Pearson Addison-Wesley. All rights reserved11-17 Iterative version of writeVertical

© 2006 Pearson Addison-Wesley. All rights reserved11-18 Recursive Methods that Return a Value Recursion is not limited to void methods A recursive method can return a value of any type An outline for a successful recursive method that returns a value is as follows: –One or more cases in which the value returned is computed in terms of calls to the same method –the arguments for the recursive calls should be intuitively "smaller" –One or more cases in which the value returned is computed without the use of any recursive calls (the base or stopping cases)

© 2006 Pearson Addison-Wesley. All rights reserved11-19 Another Powers Method The method pow from the Math class computes powers –It takes two arguments of type double and returns a value of type double The recursive method power takes two arguments of type int and returns a value of type int –The definition of power is based on the following formula: x n is equal to x n-1 * x

© 2006 Pearson Addison-Wesley. All rights reserved11-20 Another Powers Method In terms of Java, the value returned by power(x, n) for n>0 should be the same as power(x, n-1) * x When n=0, then power(x, n) should return 1 –This is the stopping case

© 2006 Pearson Addison-Wesley. All rights reserved11-21 The Recursive Method power (Part 1 of 2)

© 2006 Pearson Addison-Wesley. All rights reserved11-22 The Recursive Method power (Part 1 of 2)

© 2006 Pearson Addison-Wesley. All rights reserved11-23 Evaluating the Recursive Method Call power(2,3)

© 2006 Pearson Addison-Wesley. All rights reserved11-24 Selected Recursive Problems

© 2006 Pearson Addison-Wesley. All rights reserved11-25 Recursive Problem 1 Compute the factorial of an integer, i.e. fact(n) = n!

© 2006 Pearson Addison-Wesley. All rights reserved11-26 Recursive Problem 2 Calculate the sum of an array of integers

© 2006 Pearson Addison-Wesley. All rights reserved11-27 Recursive Problem 3 Reverse the order of the characters in a string

© 2006 Pearson Addison-Wesley. All rights reserved11-28 Recursive Problem 4 Count number of digits in an integer

© 2006 Pearson Addison-Wesley. All rights reserved11-29 Recursive Problem 5 Consider the following sequence of numbers: 1, 1, 2, 3, 5, 8, 13 Except for the first two integers, each integer is the sum of the previous two integers. This sequence is known as fibonacci numbers. Fibonacci numbers have important applications in computer science and mathematics. Write a program to produce the first n numbers of the fibonacci sequence

© 2006 Pearson Addison-Wesley. All rights reserved11-30 Recursive Problem 6 A palindrome is a phrase that reads the same forwards and backwards. For example: –radar –able was I ere I saw elba –pan a nap Write a program that answers the question, "Is this string a palindrome?"

© 2006 Pearson Addison-Wesley. All rights reserved11-31 Recursive Problem 7 print out all the permutations of a string Example: permutations of "abc": abc acb bac bca cab cba (assume no repeated letters in string) Much simpler to solve this with recursion than without.

© 2006 Pearson Addison-Wesley. All rights reserved11-32 Permutations Solution –Given the empty set { }, the only possible permutation is { } –Given the set {A}, the only possible permutation is {A} –Given the set {A, B}, the possible permutations are {AB, BA} –Given the set {A, B, C}, the possible permutations are {ABC, ACB, BAC, BCA, CAB, CBA} –Etc.

© 2006 Pearson Addison-Wesley. All rights reserved11-33 Finding all permutations of n objects To find all permutations of n objects: –Find all permutations of n-1 of those objects –Insert the remaining object into all possible positions of each permutation of n-1 objects Example: To find all permutations of 3 objects {A, B, C} –Find all permutations of 2 of the objects, say B and C : B C and C B –Insert the remaining object, A, into all possible positions (marked by ^) in each of the permutations of B and C : ^ B ^ C ^ and ^ C ^ B ^ – ABC BAC BCA ACB CAB CBA

© 2006 Pearson Addison-Wesley. All rights reserved11-34 Towers of Hanoi In a later course