The Basics of Recursion

Slides:



Advertisements
Similar presentations
Basics of Recursion Programming with Recursion
Advertisements

Copyright © 2003 Pearson Education, Inc. Slide 1.
Recursion Chapter 11. Objectives become familiar with the idea of recursion learn to use recursion as a programming tool become familiar with the binary.
1 Chapter 11 l Basics of Recursion l Programming with Recursion Recursion.
Recursion. Binary search example postponed to end of lecture.
Recursion Chapter 11 Chapter 11.
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.
Recursion.
Chapter 11 Recursion Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
Copyright © 2003 Pearson Education, Inc. Slide 1.
CS180 RECURSION March 28,2008. Announcements Project 7 : Recursive Expression Evaluators Milestone Due : 4/2/2008 Project Due : 4/9/2008 Exam 2 to be.
Slides prepared by Rose Williams, Binghamton University Chapter 11 Recursion.
Control Structures II. Why is Repetition Needed? There are many situations in which the same statements need to be executed several times. Example: Formulas.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
Iteration. Adding CDs to Vic Stack In many of the programs you write, you would like to have a CD on the stack before the program runs. To do this, you.
Chapter 11 Recursion Slides prepared by Rose Williams, Binghamton University Copyright © 2008 Pearson Addison-Wesley. All rights reserved.
Chapter 12Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 12 l Basics of Recursion l Programming with Recursion Recursion.
Strings CIS 362. What is a string? In Visual Basic fullName.
 The pool rack example could be implemented using a for loop.  It is also possible to write recursive methods that accomplish things that you might.
Chapter 11Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 11 l Basics of Recursion l Programming with Recursion Recursion.
M180: Data Structures & Algorithms in Java
Recursion Chapter 11. The Basics of Recursion: Outline Introduction to Recursion How Recursion Works Recursion versus Iteration Recursive Methods That.
Lecturer: Dr. AJ Bieszczad Chapter 11 COMP 150: Introduction to Object-Oriented Programming 11-1 l Basics of Recursion l Programming with Recursion Recursion.
Chapter 11Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 11 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.
CIS 068 Welcome to CIS 068 ! Stacks and Recursion.
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.
Chapter 5: Control Structures II J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design,
Chapter 12. Recursion Basics of Recursion Programming with Recursion Computer Programming with JAVA.
Chapter 5: Control Structures II
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.
CONTROL STATEMENTS LOOPS. WHY IS REPETITION NEEDED?  There are many situations in which the same statements need to be executed several times.  Example:
© Janice Regan, CMPT 128, February CMPT 128: Introduction to Computing Science for Engineering Students Recursion.
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.
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.
Methods Matthew Harrison. Overview ● There are five main aspects of methods... ● 1) Modifiers – public, private ● 2) Method Name ● 3) Parameters ● 4)
JAVA: An Introduction to Problem Solving & Programming, 6 th Ed. By Walter Savitch ISBN © 2012 Pearson Education, Inc., Upper Saddle River,
Chapter 13 Recursion Copyright © 2016 Pearson, Inc. All rights reserved.
Chapter Topics Chapter 16 discusses the following main topics:
Recursion Version 1.0.
to understand recursion you must understand recursion
Recursion DRILL: Please take out your notes on Recursion
Arrays in Classes and Methods
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.
Chapter 11 Recursion Slides prepared by Rose Williams, Binghamton University Kenrick Mock, University of Alaska Anchorage Copyright © 2016 Pearson Inc.
Chapter 5: Control Structures II
Repetition-Counter control Loop
Recursion Chapter 10.
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
Recursion This slide set was compiled from the Absolute Java textbook slides (Walter Savitch) and the instructor’s class materials.
Recursion Chapter 11.
CS302 - Data Structures using C++
Basics of Recursion Programming with Recursion
Recursion Chapter 11.
Comp 249 Programming Methodology
Chapter 13 Recursion Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
Recursive Thinking.
Basic Exception Handling
Presentation transcript:

The Basics of Recursion

Example of a Recursive Algorithm Assume you want to find a name in a phone book. You could open the book to the middle and if the name is on that page you are done. If not, if the name were alphabetically before the page you were looking at, you could search the first half of the book. If it were alphabetically after the current page, you could search the second half of the book. Searching half the book is just a smaller version of searching the entire book so you can use the same algorithm.

The Idea of Recursion A natural way to design an algorithm often involves using the same algorithm on one or more subcases. If a method definition contains an invocation of the very method being defined, that invocation is called a recursive call, or recursive invocation.

Another Example of Using Recursion Suppose the requirement is to take a single integer and write out the digits of the integer as words. For example, if the integer input is 223, the algorithm should write out “two two three”. If the integer is a single digit, you can use a long switch statement to write out the appropriate word.

Another Example of Using Recursion (cont’d) This task can be divided into subtasks in many ways, and not all ways make use of recursion. One way that does is the following: Output all but the last digit as words. Output the word for the last digit. The second statement can be accomplished with our long switch statement.

Another Example of Using Recursion (cont’d) If inWords is the name of our method for outputting the integer in words, we can write out algorithm as follows: inWords(number with the last digit deleted); System.out.print(digitWord(last digit) + “ “); where digitWord is a method containing the long switch statement for outputting a single word for a single digit.

Another Example of Using Recursion (cont’d) Since number/10 gives the number with the last digit removed and number%10 gives the remainder which is the last digit, we can rewrite the algorithm as follows: inWords(number/10) System.out.print(digitWord(number%10) + “ “);

Complete Code for Integer to Words Recursive Algorithm import java.util.*; public class RecursionDemo { public static void main(String[] args) { System.out.println("Enter an integer:"); Scanner keyboard = new Scanner(System.in);; int number = keyboard.nextInt( ); System.out.println("The digits in that number are:"); inWords(number); System.out.println( ); System.out.println("If you add ten to that number, "); System.out.println("the digits in the new number are:"); number = number + 10; inWords(number); System.out.println( ); } /** Precondition: number >= 0 Action: The digits in number are written out in words. */ public static void inWords(int number) { if (number < 10) System.out.print(digitWord(number) + " "); else //number has two or more digits { inWords(number/10); System.out.print(digitWord(number%10) + " "); } }

Complete Code for Integer to Words Recursive Algorithm (cont’d) /** Precondition: 0 <= digit <= 9 Returns the word for the argument digit. */ private static String digitWord(int digit) { String result = null; switch (digit) { case 0: result = "zero"; break; case 1: result = "one"; break; case 2: result = "two"; break; case 3: result = "three"; break; case 4: result = "four"; break; case 5: result = "five"; break; case 6: result = "six"; break; case 7: result = "seven"; break; case 8: result = "eight"; break; case 9: result = "nine"; break; default: System.out.println("Fatal Error."); System.exit(0); break; } return result; } }

Key to Successful Recursion A definition of a method that includes a recursive invocation of the method itself will not behave correctly unless some specific guidelines are followed. The following rules apply to most cases that involve recursion: The heart of the method definition is an if-else statement or some other branching statement that leads to different cases, depending on some property of a parameter to the method.

Key to Successful Recursion (cont’d) One or more of the branches should include a recursive invocation of the method. These recursive invocations should, in some way, solve “smaller” versions of the task. One or more branches should include no recursive invocations. These branches are the stopping cases (also known as base cases).

Infinite Recursion In order for a recursive method definition to work correctly and not produce an infinite chain of recursive calls, there must be one or more cases that, for certain values of the parameter(s), will end without producing any recursive call. That is, there must be a stopping case. When a method invocation leads to infinite recursion, your program is likely to end with an error message saying “stack overflow”.

Recursive versus Iterative Definitions Any method definition that includes a recursive call can be rewritten so that it accomplishes the same task without using recursion. The nonrecursive version typically involves a loop in place of recursion, and hence is called an iterative version. Recursive versions are usually less efficient than iterative versions, but often make programs easier to understand.

Iterative Version of Previous Example import java.util.*; public class IterativeDemo { public static void main(String[] args) { System.out.println("Enter an integer:"); Scanner keyboard = new Scanner(System.in); int number = keyboard.nextInt( ); System.out.println("The digits in that number are:"); inWords(number); System.out.println( ); System.out.println("If you add ten to that number, "); System.out.println("the digits in the new number are:"); number = number + 10; inWords(number); System.out.println( ); } /** Precondition: number >= 0 Action: The digits in number are written out in words. */ public static void inWords(int number) { int divisor = powerOfTen(number); int next = number; while (divisor >= 10) { System.out.print(digitWord(next/divisor) + " "); next = next%divisor; divisor = divisor/10; } System.out.print(digitWord(next/divisor) + " "); }

Iterative Version of Previous Example (cont’d) /** Precondition: n >= 0. Returns the number in the form "one followed by all zeros that is the same length as n." */ private static int powerOfTen(int n) { int result = 1; while(n >= 10) { result = result*10; n = n/10; } return result; }

Iterative Version of Previous Example (cont’d) private static String digitWord(int digit) { String result = null; switch (digit) { case 0: result = "zero"; break; case 1: result = "one"; break; case 2: result = "two"; break; case 3: result = "three"; break; case 4: result = "four"; break; case 5: result = "five"; break; case 6: result = "six"; break; case 7: result = "seven"; break; case 8: result = "eight"; break; case 9: result = "nine"; break; default: System.out.println("Fatal Error."); System.exit(0); break; } return result; } }

Example of a Recursive Method that Returns a Value Assume the task is to determine the number of zeros in an integer. We might write the algorithm as follows: If n is two or more digits long, then the number of zero digits in n is (the number of zeroes in n with the last digit removed) plus an additional one if the last digit is zero.

Example of a Recursive Method that Returns a Value (cont’d) import java.util.*; public class RecursionDemo2 { public static void main(String[] args) { System.out.println("Enter a nonnegative number:"); Scanner keyboard = new Scanner(System.in); int number = keyboard.nextInt( ); System.out.println(number + " contains " + numberOfZeros(number) + " zeros."); } /** Precondition: n >= 0 Returns the number of zero digits in n. */ public static int numberOfZeros(int n) { if (n == 0) return 1; else if (n < 10)//and not 0 return 0;//0 for no zeros else if (n%10 == 0) return(numberOfZeros(n/10) + 1); else //n%10 != 0 return(numberOfZeros(n/10)); } }