Building Java Programs Chapter 12 Recursion Copyright (c) Pearson 2013. All rights reserved.

Slides:



Advertisements
Similar presentations
Recursion Chapter 14. Overview Base case and general case of recursion. A recursion is a method that calls itself. That simplifies the problem. The simpler.
Advertisements

Copyright 2006 by Pearson Education 1 Building Java Programs Chapter 12: Recursion.
Copyright 2006 by Pearson Education 1 Building Java Programs Chapter 12: Recursion.
Recursion … just in case you didn’t love loops enough …
CS 206 Introduction to Computer Science II 10 / 14 / 2009 Instructor: Michael Eckmann.
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.
Slides prepared by Rose Williams, Binghamton University Chapter 11 Recursion.
CS Discrete Mathematical Structures Mehdi Ghayoumi MSB rm 132 Ofc hr: Thur, 9:30-11:30a.
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.
CSE 143 Lecture 11 Recursive Programming reading: slides created by Marty Stepp and Hélène Martin
Building Java Programs Chapter 12 Lecture 12-2: recursive programming reading:
20-1 Computing Fundamentals with C++ Object-Oriented Programming and Design, 2nd Edition Rick Mercer Franklin, Beedle & Associates, 1999 ISBN
1 BUILDING JAVA PROGRAMS CHAPTER 2 PRIMITIVE DATA AND DEFINITE LOOPS.
Recursion A method is recursive if it makes a call to itself. A method is recursive if it makes a call to itself. For example: For example: public void.
Stephen P. Carl - CS 2421 Recursion Reading : Chapter 4.
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.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
1Recursion. 2 Outline thinking recursively recursive algorithms iteration vs. recursion recursive functions integer exponentiation (pow) infinite recursion.
1 TCSS 143, Autumn 2004 Lecture Notes Recursion Koffman/Wolfgang Ch. 7, pp ,
CSE 143 Lecture 13 Recursive Programming reading: slides created by Marty Stepp
Chapter 17 Recursion Data Structures with Java © Rick Mercer Data Structures with Java © Rick Mercer.
Algorithms Java Methods A & AB Object-Oriented Programming and Data Structures Maria Litvin ● Gary Litvin Copyright © 2006 by Maria Litvin, Gary Litvin,
1 Recursion n what is it? n how to build recursive algorithms n recursion analysis n tracing simple recursive functions n hands on attempts at writing.
CSE 143 Lecture 10 Recursion reading: slides created by Marty Stepp and Hélène Martin
Programming With Java ICS201 University Of Ha’il1 Chapter 11 Recursion.
1 BUILDING JAVA PROGRAMS CHAPTER 2 PRIMITIVE DATA AND DEFINITE LOOPS.
CSE 143 Lecture 9 Recursion slides created by Alyssa Harding
Recursion in Java The answer to life’s greatest mysteries are on the last slide.
Unit 8 Search, Sort, Recursion
CSE 143 Lecture 9: introduction to recursion reading: 12.1.
Building Java Programs Chapter 12: Recursive public/private pairs Chapter 13: Searching reading: 13.3.
Recursion.
Recursion Recursion is a fundamental programming technique that can provide an elegant solution certain kinds of problems © 2004 Pearson Addison-Wesley.
Lecture 24: Recursion Building Java Programs: A Back to Basics Approach by Stuart Reges and Marty Stepp Copyright (c) Pearson All rights reserved.
Lecture 9: introduction to recursion reading: 12.1
Data Structures with Java © Rick Mercer
Lecture 10: recursive programming reading:
Building Java Programs
MSc/ICY Software Workshop , Semester 2
Recursion DRILL: Please take out your notes on Recursion
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.
Recursion
Building Java Programs
slides adapted from Marty Stepp and Hélène Martin
Chapter 12 Recursion (methods calling themselves)
Adapted from slides by Marty Stepp, Stuart Reges & Allison Obourn.
Lecture 10: recursive programming reading:
CSE 143 Lecture 11 Recursive Programming reading:
Building Java Programs
Building Java Programs
CSE 143 Lecture 11 Recursive Programming slides created by Marty Stepp
slides created by Marty Stepp and Alyssa Harding
Recursion based on slides by Alyssa Harding
Recursion Based on slides by Alyssa Harding
Lecture 14: Strings and Recursion AP Computer Science Principles
Lecture 19: Recursion Building Java Programs: A Back to Basics Approach by Stuart Reges and Marty Stepp Copyright (c) Pearson All rights reserved.
Java Programming: Chapter 9: Recursion Second Edition
Building Java Programs
CSE 143 Lecture 13 Recursive Programming reading:
slides adapted from Marty Stepp and Hélène Martin
CSE 143 Lecture 13 Recursive Programming reading:
Algorithms An algorithm is a set of instructions used to solve a specific problem In order to be useful, an algorithm must have the following properties:
Building Java Programs
Lecture 10: recursive programming reading:
slides created by Marty Stepp
Building Java Programs
Lecture 6 - Recursion.
Presentation transcript:

Building Java Programs Chapter 12 Recursion Copyright (c) Pearson All rights reserved.

2 Recursion recursion: The definition of an operation in terms of itself. –Solving a problem using recursion depends on solving smaller occurrences of the same problem. recursive programming: Writing methods that call themselves to solve problems recursively. –An equally powerful substitute for iteration (loops) –Particularly well-suited to solving certain types of problems

3 Why learn recursion? "cultural experience" - A different way of thinking of problems Can solve some kinds of problems better than iteration Leads to elegant, simplistic, short code (when used well) Many programming languages ("functional" languages such as Scheme, ML, and Haskell) use recursion exclusively (no loops)

4 Exercise (To a student in the front row) How many students total are directly behind you in your "column" of the classroom? –You have poor vision, so you can see only the people right next to you. So you can't just look back and count. –But you are allowed to ask questions of the person next to you. –How can we solve this problem? (recursively )

5 The idea Recursion is all about breaking a big problem into smaller occurrences of that same problem. –Each person can solve a small part of the problem. What is a small version of the problem that would be easy to answer? What information from a neighbor might help me?

6 Recursive algorithm Number of people behind me: –If there is someone behind me, ask him/her how many people are behind him/her. When they respond with a value N, then I will answer N + 1. –If there is nobody behind me, I will answer 0.

7 Recursion and cases Every recursive algorithm involves at least 2 cases: –base case: A simple occurrence that can be answered directly. –recursive case: A more complex occurrence of the problem that cannot be directly answered, but can instead be described in terms of smaller occurrences of the same problem. –Some recursive algorithms have more than one base or recursive case, but all have at least one of each. –A crucial part of recursive programming is identifying these cases.

8 Recursion in Java Consider the following method to print a line of * characters: // Prints a line containing the given number of stars. // Precondition: n >= 0 public static void printStars(int n) { for (int i = 0; i < n; i++) { System.out.print("*"); } System.out.println(); // end the line of output } Write a recursive version of this method (that calls itself). –Solve the problem without using any loops. –Hint: Your solution should print just one star at a time.

9 A basic case What are the cases to consider? –What is a very easy number of stars to print without a loop? public static void printStars(int n) { if (n == 1) { // base case; just print one star System.out.println("*"); } else {... } }

10 Handling more cases Handling additional cases, with no loops (in a bad way): public static void printStars(int n) { if (n == 1) { // base case; just print one star System.out.println("*"); } else if (n == 2) { System.out.print("*"); System.out.println("*"); } else if (n == 3) { System.out.print("*"); System.out.println("*"); } else if (n == 4) { System.out.print("*"); System.out.println("*"); } else... }

11 Handling more cases 2 Taking advantage of the repeated pattern (somewhat better): public static void printStars(int n) { if (n == 1) { // base case; just print one star System.out.println("*"); } else if (n == 2) { System.out.print("*"); printStars(1); // prints "*" } else if (n == 3) { System.out.print("*"); printStars(2); // prints "**" } else if (n == 4) { System.out.print("*"); printStars(3); // prints "***" } else... }

12 Using recursion properly Condensing the recursive cases into a single case: public static void printStars(int n) { if (n == 1) { // base case; just print one star System.out.println("*"); } else { // recursive case; print one more star System.out.print("*"); printStars(n - 1); }

13 "Recursion Zen" The real, even simpler, base case is an n of 0, not 1: public static void printStars(int n) { if (n == 0) { // base case; just end the line of output System.out.println(); } else { // recursive case; print one more star System.out.print("*"); printStars(n - 1); } –Recursion Zen: The art of properly identifying the best set of cases for a recursive algorithm and expressing them elegantly.

14 Exercise Write a recursive method pow accepts an integer base and exponent and returns the base raised to that exponent. –Example: pow(3, 4) returns 81 –Solve the problem recursively and without using loops.

15 pow solution // Returns base ^ exponent. // Precondition: exponent >= 0 public static int pow(int base, int exponent) { if (exponent == 0) { // base case; any number to 0th power is 1 return 1; } else { // recursive case: x^y = x * x^(y-1) return base * pow(base, exponent - 1); }

16 An optimization Notice the following mathematical property: 3 12 =531441= 9 6 = (3 2 ) = (9 2 ) 3 = ((3 2 ) 2 ) 3 –When does this "trick" work? –How can we incorporate this optimization into our pow method? –What is the benefit of this trick if the method already works?

17 pow solution 2 // Returns base ^ exponent. // Precondition: exponent >= 0 public static int pow(int base, int exponent) { if (exponent == 0) { // base case; any number to 0th power is 1 return 1; } else if (exponent % 2 == 0) { // recursive case 1: x^y = (x^2)^(y/2) return pow(base * base, exponent / 2); } else { // recursive case 2: x^y = x * x^(y-1) return base * pow(base, exponent - 1); }

18 Exercise Write a recursive method printBinary that accepts an integer and prints that number's representation in binary (base 2). –Example: printBinary(7) prints 111 –Example: printBinary(12) prints 1100 –Example: printBinary(42) prints –Write the method recursively and without using any loops. place value

19 Case analysis Recursion is about solving a small piece of a large problem. –What is in binary? Do we know anything about its representation in binary? –Case analysis: What is/are easy numbers to print in binary? Can we express a larger number in terms of a smaller number(s)? –Suppose we are examining some arbitrary integer N. if N 's binary representation is (N / 2) 's binary representation is (N % 2) 's binary representation is 1

20 printBinary solution // Prints the given integer's binary representation. // Precondition: n >= 0 public static void printBinary(int n) { if (n < 2) { // base case; same as base 10 System.out.println(n); } else { // recursive case; break number apart printBinary(n / 2); printBinary(n % 2); } –Can we eliminate the precondition and deal with negatives?

21 printBinary solution 2 // Prints the given integer's binary representation. public static void printBinary(int n) { if (n < 0) { // recursive case for negative numbers System.out.print("-"); printBinary(-n); } else if (n < 2) { // base case; same as base 10 System.out.println(n); } else { // recursive case; break number apart printBinary(n / 2); printBinary(n % 2); }