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.

Slides:



Advertisements
Similar presentations
Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. Chapter 13 – Recursion.
Advertisements

Recursion - see Recursion. RHS – SOC 2 Recursion We know that: –We can define classes –We can define methods on classes –Mehtods can call other methods.
Chapter 18 Recursion "To iterate is human, to recurse divine.", L. Peter Deutsch.
CHAPTER 13 Recursion. Recursive Solution A recursive solution  solves a problem by solving a smaller instance of the problem. Example  How do we go.
Recursive Functions The Fibonacci function shown previously is recursive, that is, it calls itself Each call to a recursive method results in a separate.
CS102 Algorithms and Programming II1 Recursion Recursion is a technique that solves a problem by solving a smaller problem of the same type. A recursive.
16-Jun-15 Recursion. 2 Definitions I A recursive definition is a definition in which the thing being defined occurs as part of its own definition Example:
Recursion. Objectives At the conclusion of this lesson, students should be able to Explain what recursion is Design and write functions that use recursion.
1 Introduction to Recursion  Introduction to Recursion  Example 1: Factorial  Example 2: Reversing Strings  Example 3: Fibonacci  Infinite Recursion.
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.
28-Jun-15 Recursion. 2 Definitions I A recursive definition is a definition in which the thing being defined occurs as part of its own definition Example:
Unit 7 1 Unit 7: Recursion H Recursion is a fundamental programming technique that can provide an elegant solution to a certain kinds of problems H In.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 6 Repetition Statements.
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.
ECE122 L9: While loops March 1, 2007 ECE 122 Engineering Problem Solving with Java Lecture 9 While Loops.
Recursion In general there are two approaches to writing repetitive algorithms. One uses loops(while, do while and for): the other uses recursion. Recursion.
Recursion & Collections API Recursion Revisited Programming Assignments using the Collections API.
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
Recursion James Wright St Peter’s Secondary School 733 Parkhill Road West Peterborough,Ontario K9J-8M4
Building Java Programs Chapter 12 Lecture 12-2: recursive programming reading:
A Computer Science Tapestry 1 Recursion (Tapestry 10.1, 10.3) l Recursion is an indispensable technique in a programming language ä Allows many complex.
Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Chapter 13 - Recursion.
Recursion l Powerful Tool l Useful in simplifying a problem (hides details of a problem) l The ability of a function to call itself l A recursive call.
COSC 2006 Data Structures I Recursion II
Cosc236/recursion1 Recursion Recursive method calls itself Recursion frequently occurs in mathematics Recursive definition –2 parts base part (basis) recursive.
Slides prepared by Rose Williams, Binghamton University ICS201 Lecture 19 : Recursion King Fahd University of Petroleum & Minerals College of Computer.
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.
Recursion Self-Referencing Functions. Problem # 1 Write a function that, given n, computes n! n! == (n-1) n n! == 1  2 ...  (n-1)  nExample:
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.
Computer Science Department Data Structure & Algorithms Lecture 8 Recursion.
Reading – Chapter 10. Recursion The process of solving a problem by reducing it to smaller versions of itself Example: Sierpinski’s TriangleSierpinski’s.
1 TCSS 143, Autumn 2004 Lecture Notes Recursion Koffman/Wolfgang Ch. 7, pp ,
CSC 212 More Recursion, Stacks, & Queues. Linear Recursion Test for the bases cases  At least one base case needs to be defined If not at a base case,
1 CompSci 105 SS 2005 Principles of Computer Science Lecture 6: Recursion Lecturer: Santokh Singh Assignment 1 due tomorrow. Should have started working.
Java Basics Hussein Suleman March 2007 UCT Department of Computer Science Computer Science 1015F.
1 Recursion Recursion is a powerful programming technique that provides elegant solutions to certain problems. Chapter 11 focuses on explaining the underlying.
1 Recursion. 2 Chapter 15 Topics  Meaning of Recursion  Base Case and General Case in Recursive Function Definitions  Writing Recursive Functions with.
October 3, 2001CSE 373, Autumn Mathematical Background Exponents X A X B = X A+B X A / X B = X A-B (X A ) B = X AB X N +X N = 2X N 2 N +2 N = 2 N+1.
Recursion A recursive definition is one which uses the word or concept being defined in the definition itself Example: “A computer is a machine.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 5 Control Structures II: Repetition.
Review of Recursion  a recursive method calls itself  to prevent infinite recursion you need to ensure that: 1. the method reaches a base case 2. each.
Int fact (int n) { If (n == 0) return 1; else return n * fact (n – 1); } 5 void main () { Int Sum; : Sum = fact (5); : } Factorial Program Using 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.
1 Recursion and induction We teach these early, instead of new object- oriented ideas, so that those who are new to Java can have a chance to catch up.
Let’s try it one more time!. Allan Technique Programming Recursively 1.Decide that the problem needs a recursive solution. 2.Decide specifically what.
CSC 143 P 1 CSC 143 Recursion [Chapter 5]. CSC 143 P 2 Recursion  A recursive definition is one which is defined in terms of itself  Example:  Compound.
© 2004 Pearson Addison-Wesley. All rights reserved October 5, 2007 Arrays ComS 207: Programming I (in Java) Iowa State University, FALL 2007 Instructor:
Recursion Powerful Tool
Recursion.
CSC 205 Programming II Lecture 8 Recursion.
Recursion Version 1.0.
Lecture 10: recursive programming reading:
Announcements Final Exam on August 17th Wednesday at 16:00.
Lecture 10: recursive programming reading:
CSE 143 Lecture 11 Recursive Programming reading:
Recursion.
Building Java Programs
Recursion Chapter 18.
Module 4 Loops.
slides created by Marty Stepp and Alyssa Harding
Recursion Problems.
CSE 143 Lecture 13 Recursive Programming reading:
CSE 143 Lecture 13 Recursive Programming reading:
Chapter 18 Recursion.
Recursion Method calling itself (circular definition)
Self-Referencing Functions
Presentation transcript:

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 printDown (int n){ public void printDown (int n){ System.out.println( n); System.out.println( n); printDown(n-1); printDown(n-1);} Is a recursive method. In fact, it ‘recurses’ infinately….

A method which recurses infinately is not of much use. There are many problems which can be solved recursively and, in fact, be coded more simply by the use of recursion. Let’s first learn to PROPERLY use recursion on familiar applications…

Designing a recursive solution The idea behind using recursion to solve a problem is to simplify the solution by defining the problem in terms of itself. defining the problem in terms of itself. For example: For example: Suppose we want to write a method power(x,n), which raises x to the nth power. And suppose we don’t know how to compute X n, but we know that X n = X * X n-1. Suppose we want to write a method power(x,n), which raises x to the nth power. And suppose we don’t know how to compute X n, but we know that X n = X * X n-1. We have start of a recursive solution!! We have start of a recursive solution!!

X n = X * X n-1 We might try writing the power method: We might try writing the power method: public int power (int x, int n) { public int power (int x, int n) { return x * power(x, n-1); return x * power(x, n-1); } This is logical, because IF we had a power method, the return statement is correct …. And we ARE writing a power method. This is logical, because IF we had a power method, the return statement is correct …. And we ARE writing a power method. There is only one problem …………… There is only one problem ……………

Let’s try our method by tracing a call to power(3,3) power(3,3) returns 3 * power (3,2) need to call power(3,2) to find result to find result power(3,2) returns 3 * power (3,1) need to call power(3,1) to find result to find result power(3,1) returns 3 * power (3,0) need to call power(3,0) to find result to find result power(3,0) returns 3 * power (3,-1) need to call power(3,1) to find result to find result We could do this all day …. Infinite recursion again!!

A method which uses recursion should ALWAYS have at least one path which does not recurse in order to avoid infinite recursion. Where do we come up with that??? We must find ONE case of the problem in which we know the solution. For example, we KNOW X 1 = X. We must find ONE case of the problem in which we know the solution. For example, we KNOW X 1 = X. public int power (int x, int n) { if ( n == 1) if ( n == 1) return x; return x; else else return x * power(x, n-1); return x * power(x, n-1); }

Let’s try our method by tracing a call to power(3,3) power(3,3) returns 3 * power (3,2) need to call power(3,2) to find result to find result power(3,2) returns 3 * power (3,1) need to call power(3,1) power(3,2) returns 3 * power (3,1) need to call power(3,1) to find result power(3,1) returns 3 to find result power(3,1) returns 3 So, that means power(3,2) return 3 * 3 (or 9) power(3,2) return 3 * 3 (or 9) power(3,3) returns 3 * 9 (or 27) power(3,3) returns 3 * 9 (or 27)

Another recursive solution Suppose we want to write a method factorial(n) which computes n! (mathematical symbol defined as n* n- 1* n-2 *.. * 1, and 0! = 1. Suppose we want to write a method factorial(n) which computes n! (mathematical symbol defined as n* n- 1* n-2 *.. * 1, and 0! = 1. To avoid infinite recursion we need to think of something we know. To avoid infinite recursion we need to think of something we know. We know: 0! = 1 We know: 0! = 1 Now, define the unknown part of the solution in terms of the solution itself. N! = N * (N-1)! Now, define the unknown part of the solution in terms of the solution itself. N! = N * (N-1)!

public int factorial ( int n) { if ( n == 0) if ( n == 0) return 1; return 1; else else return n * factorial( n-1); return n * factorial( n-1); } Trace it for factorial(4) and check if it works!! The solution should be 24.

Another recursive solution Suppose we want to write a method which printDown(n) which prints the values from n downto 1 … without using a loop. Suppose we want to write a method which printDown(n) which prints the values from n downto 1 … without using a loop. We know: If n is 1, we just want to print 1 Define the unknown part of the solution in terms of the method itself. Define the unknown part of the solution in terms of the method itself. print n print n call printDown(n-1) to print the rest of the values call printDown(n-1) to print the rest of the values

public void printDown( int n) { if ( n == 1) if ( n == 1) System.out.println(1); System.out.println(1); else{ else{ System.out.println(n); System.out.println(n); printDown(n-1); printDown(n-1); } Try a call to printDown(5). What is the maximum number of calls to printDown that were active at once?? I counted 5.

Another recursive solution Suppose we want to write a method named printRev(s) which prints the characters in the String s in reverse … without using a loop. Suppose we want to write a method named printRev(s) which prints the characters in the String s in reverse … without using a loop. We know: If s has a length of 1, we just print s Define the unknown part of the solution in terms of the method itself. Define the unknown part of the solution in terms of the method itself. call printRev(rest of the string) to print the rest of call printRev(rest of the string) to print the rest of the string in reverse the string in reverse print the first character print the first character

public void printRev( String s) { if ( s.length() == 1) if ( s.length() == 1) System.out.print(s); System.out.print(s); else{ else{ printRev(s.substring(1)); printRev(s.substring(1)); System.out.print(s.charAt(0)); System.out.print(s.charAt(0)); }} Try a call to printRev(“java”). What is the maximum number of calls to printRev that were active at once?? I counted 4.

Clearly, these solutions we have been looking at can be much more simply written using a loop. Additionally, the effect of a method call on execution time makes these solutions highly inefficient …. These problems were not best solved using recursion. But, there ARE problems that are much more simply solved, often at no cost to efficiency, using recursion.

Palindromes Design a method that will determine if a String is a palindrome (reads the same forward and backward). For example, Madame I’m Adam is a palindrome. Our method signature will look like this: public boolean palindrome(String s) public boolean palindrome(String s) We will not worry about punctuation for now … assume that the String has been scanned and all punctuation removed, and letters are all lower case.

Palindromes continued What do we know?? What do we know?? if the string has one character it is a palindrome if the string has one character it is a palindrome if the string is empty it is implicitly a palindrome if the string is empty it is implicitly a palindrome What if we Had a method palindrome …. if the first and last character are the same if the first and last character are the same then then if the substring in between those chars is a if the substring in between those chars is a palindrome palindrome the string is a palindrome the string is a palindrome else else it string is not a palindrome it string is not a palindrome

Palindromes continued public boolean palindrome(String s){ if (s.length() <= 1) if (s.length() <= 1) return true; return true; else{ else{ char first = s.charAt(0); char first = s.charAt(0); char last = s.charAt(s.length() -1); char last = s.charAt(s.length() -1); if (first == last) if (first == last) return palindrome(s.substring(1, s.length() -1); return palindrome(s.substring(1, s.length() -1); else else return false; return false; }}