Recursion Road Map Introduction to Recursion Recursion Example #1: World’s Simplest Recursion Program Visualizing Recursion –Using Stacks Recursion Example.

Slides:



Advertisements
Similar presentations
Types of Recursive Methods
Advertisements

Fundamentals of Computer Science Lecture 14: Recursion Instructor: Evan Korth New York University.
Search and Recursion pt. 2 CS221 – 2/25/09. How to Implement Binary Search Take a sorted data-set to search and a key to search for Start at the mid-point.
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.
Recursion Chapter 7. Spring 2010CS 2252 Chapter Objectives To understand how to think recursively To learn how to trace a recursive method To learn how.
Fundamentals of Computer Science Lecture 14: Recursion Instructor: Evan Korth New York University.
Introduction to Computers and Programming Lecture 4: Mathematical Operators New York University.
Slides prepared by Rose Williams, Binghamton University Chapter 11 Recursion.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ETC - 1 What comes next? Recursion (Chapter 15) Recursive Data Structures.
1 CSCD 300 Data Structures Recursion. 2 Proof by Induction Introduction only - topic will be covered in detail in CS 320 Prove: N   i = N ( N + 1.
Slides prepared by Rose Williams, Binghamton University Chapter 11 Recursion.
Recursion. 2 CMPS 12B, UC Santa Cruz Solving problems by recursion How can you solve a complex problem? Devise a complex solution Break the complex problem.
Fall 2007CS 2251 Recursion Chapter 7. Fall 2007CS 2252 Chapter Objectives To understand how to think recursively To learn how to trace a recursive method.
Chapter 10 Recursion. Copyright © 2005 Pearson Addison-Wesley. All rights reserved Chapter Objectives Explain the underlying concepts of recursion.
CS 106 Introduction to Computer Science I 03 / 30 / 2007 Instructor: Michael Eckmann.
1 Recursion Recursive Thinking Recursive Programming Recursion versus Iteration Direct versus Indirect Recursion More on Project 2 Reading L&C 10.1 – 10.4.
Recursion A recursive function is a function that calls itself either directly or indirectly through another function. The problems that can be solved.
Recursion Chapter 7. Chapter 7: Recursion2 Chapter Objectives To understand how to think recursively To learn how to trace a recursive method To learn.
Recursion Chapter 7. Chapter 7: Recursion2 Chapter Objectives To understand how to think recursively To learn how to trace a recursive method To learn.
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.
Prof. S.M. Lee Department of Computer Science. Answer:
19-Aug-15 Simple Recursive Algorithms. 2 A short list of categories Algorithm types we will consider include: Simple recursive algorithms Backtracking.
Recursion Examples Fundamentals of CS Case 1: Code /* Recursion: Case 1 */ #include void count (int index); main () { count (0); getchar(); } void count.
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
Department of Computer Science and Engineering, HKUST 1 HKUST Summer Programming Course 2008 Recursion.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 12: Recursion Problem Solving, Abstraction, and Design using C++
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.
Functions and an Introduction to Recursion.  Recursive function ◦ A function that calls itself, either directly, or indirectly (through another function)
Chapter 7 Recursion Recursive methods Recursion in two- dimensional grids Recursive helper method Analysis of recursive algorithms.
Slides prepared by Rose Williams, Binghamton University ICS201 Lecture 19 : Recursion King Fahd University of Petroleum & Minerals College of Computer.
1 Joe Meehean.  call themselves directly  or indirectly void f(){... f();... } void g(){... h();... } void h(){... g();... }
224 3/30/98 CSE 143 Recursion [Sections 6.1, ]
Chapter 8 Recursion Modified.
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.
1 TCSS 143, Autumn 2004 Lecture Notes Recursion Koffman/Wolfgang Ch. 7, pp ,
1 Wright State University, College of Engineering Dr. T. Doom, Computer Science & Engineering CS 241 Computer Programming II CS 241 – Computer Programming.
Recursion. What is recursion? Rules of recursion Mathematical induction The Fibonacci sequence Summary Outline.
Dale Roberts CSCI N305 Functions Recursion Department of Computer and Information Science, School of Science, IUPUI.
CSC 221: Recursion. Recursion: Definition Function that solves a problem by relying on itself to compute the correct solution for a smaller version of.
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.
© Janice Regan, CMPT 128, February CMPT 128: Introduction to Computing Science for Engineering Students Recursion.
A Brief Introduction to Recursion. Recursion Recursive methods … –methods that call themselves! –They can only solve a base case –So, you divide a problem.
chap10 Chapter 10 Recursion chap10 2 Recursive Function recursive function The recursive function is a kind of function that calls.
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.
CMSC201 Computer Science I for Majors Lecture 19 – Recursion
Recursion.
Chapter 13 Recursion Copyright © 2016 Pearson, Inc. All rights reserved.
Recursion Topic 5.
Introduction to Recursion
Introduction to Recursion
Chapter 10 Recursion Instructor: Yuksel / Demirer.
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.
Lesson #6 Modular Programming and Functions.
Lesson #6 Modular Programming and Functions.
CMSC201 Computer Science I for Majors Lecture 18 – Recursion
Java 4/4/2017 Recursion.
Java Software Structures: John Lewis & Joseph Chase
Lesson #6 Modular Programming and Functions.
CMSC201 Computer Science I for Majors Lecture 16 – Recursion
MSIS 655 Advanced Business Applications Programming
Recursion Data Structures.
CMSC201 Computer Science I for Majors Lecture 19 – Recursion
Chapter 12 Supplement: Recursion with Java 1.5
RECURSION Annie Calpe
Lesson #6 Modular Programming and Functions.
Presentation transcript:

Recursion

Road Map Introduction to Recursion Recursion Example #1: World’s Simplest Recursion Program Visualizing Recursion –Using Stacks Recursion Example #2 Computing Factorials –Iterative Approach Computing Factorials –Recursive Approach

Introduction to Recursion

"Normally", we have methods that call other methods. –For example, the main() method calls some “ square()” method. Recursive Method: –A recursive method is a method that calls itself. -a(), and b() are mutually recursive if a() calls b(), and b() calls a() main() square() compute()

Why use Recursive Methods? In computer science, some problems are more easily solved by using recursive methods. For example: –Traversing through a directory or file system. –Traversing through a tree of search results. –Some sorting algorithms recursively sort data

World’s Simplest Recursion Program

public class Recursion { public static void main (String args[]) { count(0); System.out.println(); } public static void count (int index) { System.out.print(index); if (index < 2) count(index+1); } This program simply counts from 0-2: and prints: 012 This is where the recursion occurs. You can see that the count() method calls itself.

Visualizing Recursion To understand how recursion works, it helps to visualize what’s going on. To help visualize, we will use a common concept called the Stack. A stack basically operates like a container of trays in a cafeteria. It has only two operations: –Push: you can push something onto the stack. –Pop: you can pop something off the top of the stack.

Stacks Time: 0 Empty Stack Time 1: Push “2” 2 Time 2: Push “8” 2 8 Time 3: Pop: Gets 8 2 The diagram below shows a stack over time. We perform two pushes (of 2 and then of 8), and one pop. Time 4: Pop: Gets 2

Stacks and Methods When you run a program, the computer creates a stack for you. Each time you invoke a method, the method is placed on top of the stack. When the method returns or exits, the method is popped off the stack. The diagram on the next page shows a sample stack for a simple Java program.

Stacks and Methods Time: 0 Empty Stack Time 1: Push: main() main() Time 2: Push: square() main() square() Time 3: Pop: square() returns a value. method exits. main() Time 4: Pop: main() returns a value. method exits. This is called an activation record or stack frame. Usually, this actually grows downward.

Stacks and Recursion Each time a method is called, you push the method on the stack. Each time the method returns or exits, you pop the method off the stack. If a method calls itself recursively, you just push another copy of the method onto the stack. We therefore have a simple way to visualize how recursion really works.

Back to the Simple Recursion Program Here’s the code again. Now, that we understand stacks, we can visualize the recursion. public class Recursion { public static void main (String args[]) { count(0); System.out.println(); } public static void count (int index) { System.out.print(index); if (index < 2) count(index+1); }

Stacks and Recursion in Action Time: 0 Empty Stack Time 1: Push: main() main() Time 2: Push: count(0) main() count(0) Time 3: Push: count(1) Inside count(0): print (index);  0 if (index < 2) count(index+1); Inside count(1): print (index);  1 if (index < 2) count(index+1); main() count(0) count(1) Time 4: Push: count(2) main() count(0) count(1) Inside count(2): print (index);  2 if (index < 2) count(index+1); This condition now fails! Hence, recursion stops, and we proceed to pop all methods off the stack,one by one. count(2) Times 5-8: Pop everything one by one …

Recursion, Variation 1 What will the following program do? public class RecursionVar1 { public static void main (String args[]) { count(3); System.out.println(); } public static void count (int index) { System.out.print(index); if (index < 2) count(index+1); }

Recursion, Variation 2 What will the following program do? public class RecursionVar2 { public static void main (String args[]) { count(0); System.out.println(); } public static void count (int index) { if (index < 2) count(index+1); System.out.print(index); } Note that the print statement has been moved to the end of the method.

Recursion, Variation 3 What will the following program do? public class RecusionVar3 { public static void main (String args[]) { count(3); System.out.println(); } public static void count (int index) { if (index > 2) count(index+1); System.out.print(index); }

18 First two rules of recursion Base case: You must always have some base case which can be solved without recursion Making Progress: For cases that are to be solved recursively, the recursive call must always be a case that makes progress toward the base case.

19 Problem: Not working towards base case In variation #3, we do not work towards our base case. This causes infinite recursion and will cause our program to crash. Java throws a StackOverflowError exception. In some other languages this is a fatal error.

Recursion Example #2

public class Recursion2 { public static void main (String args[]) { upAndDown(1); System.out.println(); } public static void upAndDown (int n) { System.out.print ("\nLevel: " + n); if (n < 4) upAndDown (n+1); System.out.print ("\nLEVEL: " + n); } Recursion occurs here.

Computing Factorials

Factorials Computing factorials are a classic problem for examining recursion. A factorial is defined as follows: n! = n * (n-1) * (n-2) …. * 1; For example: 1! = 1 2! = 2 * 1 = 2 3! = 3 * 2 * 1 = 6 4! = 4 * 3 * 2 * 1 = 24 5! = 5 * 4 * 3 * 2 * 1 = 120 If you study this table closely, you will start to see a pattern.

Seeing the Pattern Seeing the pattern in the factorial example is difficult at first. But, once you see the pattern, you can apply this pattern to create a recursive solution to the problem. Divide a problem up into: –What we know (call this the base case) –Making progress towards the base Each step resembles original problem The method launches a new copy of itself (recursion step) to make the progress.

Factorials Computing factorials are a classic problem for examining recursion. A factorial is defined as follows: n! = n * (n-1) * (n-2) …. * 1; For example: 1! = 1 (Base Case) 2! = 2 * 1 = 2 3! = 3 * 2 * 1 = 6 4! = 4 * 3 * 2 * 1 = 24 5! = 5 * 4 * 3 * 2 * 1 = 120 If you study this table closely, you will start to see a pattern. The pattern is as follows: You can compute the factorial of any number (n) by taking n and multiplying it by the factorial of (n-1). For example: 5! = 5 * 4! (which translates to 5! = 5 * 24 = 120)

Recursive Solution public class FindFactorialRecursive { public static void main (String args[]) { for (int i = 1; i < 10; i++) System.out.println ( i + "! = " + findFactorial(i)); } public static int findFactorial (int number) { if ( (number == 1) || (number == 0) ) return 1; else return (number * findFactorial (number-1)); } Base Case. Making progress

Finding the factorial of 3 Time 2: Push: fact(3) main() fact(3) Time 3: Push: fact(2) Inside findFactorial(3): if (number <= 1) return 1; else return (3 * factorial (2)); main() fact(3) fact(2) Time 4: Push: fact(1) Inside findFactorial(2): if (number <= 1) return 1; else return (2 * factorial (1)); main() fact(3) fact(2) fact(1) Inside findFactorial(1): if (number <= 1) return 1; else return (1 * factorial (0)); Time 5: Pop: fact(1) returns 1. main() fact(3) fact(2) 1 Time 6: Pop: fact(2) returns 2. main() fact(3) 2 Time 7: Pop: fact(3) returns 6. main() 6

28 Recursion pros and cons All recursive solutions can be implemented without recursion. Recursion is "expensive". The expense of recursion lies in the fact that we have multiple activation frames and the fact that there is overhead involved with calling a method. If both of the above statements are true, why would we ever use recursion. In many cases, the extra "expense" of recursion is far outweighed by a simpler more clear algorithm which leads to an implementation that is easier to code. Ultimately, the recursion is eliminated when the compiler creates assembly language (it does this by implementing the stack).

29 Tail recursion Tail recursion is when the last line of a method makes the recursive call. In this case, you have multiple active stack frames which are unnecessary because they have finished their work. It is easy to rid you program of this type of recursion. These two steps will do so: –Enclose the body of the methods in a while loop –Replace the recursive call with an assignment statement for each method argument. Most compilers do this for you. Note: I said "most".

30 Revisit world's simplest recursion public class Recursion { public static void main (String a[]) { count(0); System.out.println(); } public static void count (int index) { System.out.print(index); if (index < 2) count(index+1); } First we re-arrange the method by reversing the if condition public class Recursion { public static void main (String args[]) { count(0); System.out.println(); } public static void count (int index) { System.out.print(index); if (index >= 2) return; else count(index+1); }

31 Revisit world's simplest recursion public class Recusion1V0 { public static void main (String args[]) { count(0); System.out.println(); } public static void count (int index) { while (true) { System.out.print(index); if (index >= 2) return; else index ++; } Next we follow our two steps public class Recursion { public static void main (String args[]) { count(0); System.out.println(); } public static void count (int index) { System.out.print(index); if (index >= 2) return; else count(index+1); }

32 Example Using Recursion: The Fibonacci Series Fibonacci series –Each number in the series is sum of two previous numbers e.g., 0, 1, 1, 2, 3, 5, 8, 13, 21… fibonacci(0) = 0 fibonacci(1) = 1 fibonacci(n) = fibonacci(n - 1) + fibonacci( n – 2 ) fibonacci(0) and fibonacci(1) are base cases –Golden ratio (golden mean)  2003 Prentice Hall, Inc. All rights reserved.

33 import javax.swing.JOptionPane; public class FibonacciTest { public static void main (String args[]) { long number, fibonacciValue; String numberAsString; numberAsString = JOptionPane.showInputDialog("What Fib value do you want?"); number = Long.parseLong( numberAsString ); fibonacciValue = fibonacci( number ); System.out.println (fibonacciValue); System.exit (0); } // recursive declaration of method fibonacci public static long fibonacci( long n ) { if ( n == 0 || n == 1 ) return n; else return fibonacci( n - 1 ) + fibonacci( n - 2 ); } // end method fibonacci } // end class FibonacciTest  2003 Prentice Hall, Inc. All rights reserved.

34 Four basic rules of recursion Base case: You must always have some base case which can be solved without recursion Making Progress: For cases that are to be solved recursively, the recursive call must always be a case that makes progress toward the base case. Design Rule: Assume that the recursive calls work. Compound Interest Rule: Never duplicate work by solving the same instance of a problem in separate recursive calls. From Data Structures and Algorithms by Mark Allen Weiss

35 Fibonacci problem Which rule do we break in the Fibonacci solution?

36 import javax.swing.JOptionPane; public class FibonacciTest { static long [] array = new long [100]; public static void main (String args[]) { long number, fibonacciValue; String numberAsString; numberAsString = JOptionPane.showInputDialog(“Enter Fib value"); number = Long.parseLong( numberAsString ); fibonacciValue = fibonacci( number ); System.out.println (fibonacciValue); System.exit (0); } // recursive declaration of method fibonacci public static long fibonacci( long n ) { if ( n == 0 || n == 1 ) return n; else if (array[(int)n] != 0) return array[(int)n]; else { array[(int)n] = fibonacci( n - 1 ) + fibonacci( n - 2 ); return array[(int)n]; } } // end method fibonacci } // end class FibonacciTest This technique is called serialization

37 One more thing to watch out for Circular recursion occurs when we stop making progress towards the base case. For example: –We continuously call a(x) from within a(x) –a(x) calls a(x+1) then a(x+1) calls a(x) from Mark Weis materials