10/14/2015cosc237/recursion1 Recursion A method of defining a concept which refers to the concept itself A method of solving a problem by reducing it to.

Slides:



Advertisements
Similar presentations
C++ Programming:. Program Design Including
Advertisements

Recursion. Binary search example postponed to end of lecture.
Programming with Recursion
Recursion. Learn about recursive definitions Explore the base case and the general case of a recursive definition Learn about recursive algorithms Lecture.
Chapter 10 Recursion. Copyright © 2005 Pearson Addison-Wesley. All rights reserved Chapter Objectives Explain the underlying concepts of 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.
Recursion.
1 Chapter 7 Recursion. 2 What Is Recursion? l Recursive call A method call in which the method being called is the same as the one making the call l Direct.
Data Structures Using C++1 Chapter 6 Recursion. Data Structures Using C++2 Chapter Objectives Learn about recursive definitions Explore the base case.
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with Java: Early Objects Third Edition by Tony Gaddis Chapter.
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.
CS212: DATASTRUCTURES Lecture 3: Recursion 1. Lecture Contents 2  The Concept of Recursion  Why recursion?  Factorial – A case study  Content of a.
1 C++ Plus Data Structures Nell Dale Chapter 7 Programming with Recursion Slides by Sylvia Sorkin, Community College of Baltimore County - Essex Campus.
Data Structures Using C++1 Chapter 6 Recursion. Data Structures Using C++2 Chapter Objectives Learn about recursive definitions Explore the base case.
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 17: Recursion.
Chapter 13 Recursion. Topics Simple Recursion Recursion with a Return Value Recursion with Two Base Cases Binary Search Revisited Animation Using Recursion.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
© 2010 Pearson Addison-Wesley. All rights reserved. Addison Wesley is an imprint of Chapter 15: Recursion Starting Out with Java: From Control Structures.
Chapter 14: Recursion J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design, Second Edition Second Edition.
Copyright © 2011 Pearson Education, Inc. Starting Out with Java: Early Objects Fourth Edition by Tony Gaddis Chapter 14: Recursion.
1 CS 132 Spring 2008 Chapter 6 Recursion Read p Skip example 6-3 (Fibonacci), 6-4 (Hanoi) Read example 6-5 (p. 387)
Chapter 9: Recursion1 CHAPTER 9 RECURSION. Recursion  Concept of recursion  A recursive: Benefit and Cost  Comparison : Iterative and recursive functions.
Cosc236/recursion1 Recursion Recursive method calls itself Recursion frequently occurs in mathematics Recursive definition –2 parts base part (basis) recursive.
1 Programming with Recursion Slides by Sylvia Sorkin, Community College of Baltimore County - Essex Campus and Robert Moyer, Montgomery County Community.
1 Lecture 14 Chapter 18 - Recursion. 2 Chapter 18 Topics l Meaning of Recursion l Base Case and General Case in Recursive Function Definitions l Writing.
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.
1 C++ Plus Data Structures Nell Dale Chapter 7 Programming with Recursion Modified from the slides by Sylvia Sorkin, Community College of Baltimore County.
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.
1 C++ Plus Data Structures Nell Dale Chapter 7 Programming with Recursion Slides by Sylvia Sorkin, Community College of Baltimore County - Essex Campus.
Chapter 14 Recursion. Chapter Objectives Learn about recursive definitions Explore the base case and the general case of a recursive definition Learn.
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 17: Recursion.
Reading – Chapter 10. Recursion The process of solving a problem by reducing it to smaller versions of itself Example: Sierpinski’s TriangleSierpinski’s.
CS212: DATASTRUCTURES Lecture 3: Recursion 1. Lecture Contents 2  The Concept of Recursion  Why recursion?  Factorial – A case study  Content of a.
Chapter 8 Recursion Modified.
Recursion Part 3 CS221 – 2/27/09. Recursion A function calls itself directly: Test() { … Test(); … }
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.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 13 Recursion.
Data Structures Using Java1 Chapter 5 Recursion. Data Structures Using Java2 Chapter Objectives Learn about recursive definitions Explore the base case.
© 2011 Pearson Education, publishing as Addison-Wesley Chapter 8: Recursion Presentation slides for Java Software Solutions for AP* Computer Science 3rd.
1 Recursion. 2 Chapter 15 Topics  Meaning of Recursion  Base Case and General Case in Recursive Function Definitions  Writing Recursive Functions with.
Recursion. 2 Overview  Learn about recursive definitions  Explore the base case and the general case of a recursive definition  Discover recursive.
Chapter 15: Recursion. Objectives In this chapter, you will: – Learn about recursive definitions – Explore the base case and the general case of a recursive.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 16: Recursion.
Chapter 7 Programming with Recursion. What Is Recursion? Recursive call A method call in which the method being called is the same as the one.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 12 Recursion.
Programming With Java ICS201 University Of Ha’il1 Chapter 11 Recursion.
Recursion Chapter 17 Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013.
Chapter 15: Recursion. Recursive Definitions Recursion: solving a problem by reducing it to smaller versions of itself – Provides a powerful way to solve.
JAVA: An Introduction to Problem Solving & Programming, 7 th Ed. By Walter Savitch ISBN © 2015 Pearson Education, Inc., Upper Saddle River,
Chapter 15: Recursion. Objectives In this chapter, you will: – Learn about recursive definitions – Explore the base case and the general case of a recursive.
Maitrayee Mukerji. Factorial For any positive integer n, its factorial is n! is: n! = 1 * 2 * 3 * 4* ….* (n-1) * n 0! = 1 1 ! = 1 2! = 1 * 2 = 2 5! =
CS 116 Object Oriented Programming II Lecture 13 Acknowledgement: Contains materials provided by George Koutsogiannakis and Matt Bauer.
Data Structures I (CPCS-204) Week # 5: Recursion Dr. Omar Batarfi Dr. Yahya Dahab Dr. Imtiaz Khan.
Recursion CS 244 Brent M. Dingle, Ph.D. Game Design and Development Program Department of Mathematics, Statistics, and Computer Science University of Wisconsin.
Programming with Recursion
Recursion.
Chapter 15 Recursion.
Recursion DRILL: Please take out your notes on Recursion
Chapter 15 Recursion.
Java Programming: Program Design Including Data Structures
Data Structures Using Java
Programming with Recursion
Recursion Chapter 11.
Chapter 18-3 Recursion Dale/Weems.
C++ Programming: From Problem Analysis to Program Design, Fifth Edition Chapter 17: Recursion.
Java Programming: Chapter 9: Recursion Second Edition
Chapter 18 Recursion.
Recursion.
Presentation transcript:

10/14/2015cosc237/recursion1 Recursion A method of defining a concept which refers to the concept itself A method of solving a problem by reducing it to smaller versions of itself A powerful, elegant, efficient way to solve certain classes of programming problems A recursive function calls itself

10/14/2015cosc237/recursion2 Recursive definitions Relative: x is a relative of y iff (if and only if) x is y’s parent x is y’s child x is y’s spouse x is a relative of a relative of y

10/14/2015cosc237/recursion3 Recursive definitions cont’d Natural numbers 1 is a natural number if i is an natural number, then i+1 is a natural number Definition in which a problem is expressed in terms of a smaller version of itself Has one or more base cases

10/14/2015cosc237/recursion4 Example 1: void message() //infinite recursive function { System.out.println("This is a recursive function.)"; message(); }

10/14/2015cosc237/recursion5 Example 2: void message(int times) { if (times > 0) { System.out.println("This is a recursive function.)"; message(times -1); }

10/14/2015cosc237/recursion6 message (4); // Each call creates an activation record or frame. 1st call times: 4 2nd call times: 3 3rd call times: 2 4th call times: 1 5th call times: 0

10/14/2015cosc237/recursion7 Recursion requires 1. base case 2. general case

8 General format for Many Recursive Functions if (some easily-solved condition) // base case solution statement else // general case recursive function call

10/14/2015cosc237/recursion9 Base part – states one or more cases that satisfy the definition –No base->infinite recursion recursive part –states how to apply the definition to satisfy other cases –with repeated applications, reduces to base implicitly: nothing else satisfies the definition

10/14/2015cosc237/recursion10 Example #3: Find the sum of all int numbers between 1 and n. Sum(5) = = 15 Base case: Sum (1) = 1 General Case: Sum (2) = = Sum(1) + 2 = Sum (n-1) + n

11 Finding the Sum of the Numbers from 1 to n int Summation ( int n ) { if ( n == 1)// base case return 1 ; else// general case return ( n + Summation ( n - 1 ) ) ; } 11

10/14/2015cosc237/recursion12 Exercises Write a function using recursion to print numbers from n to 0. Write a function using recursion to print numbers from 0 to n. (You just need to shift one line in the program above)

10/14/2015cosc237/recursion13 Solution: //n to 0 void Print(int n) { System.out.println(n ); if (n <= 0) return; Print(n-1); } //0 to n void Print(int n) { if (n > 0) Print(n-1); System.out.println(n ); }

10/14/2015cosc237/recursion14 Example #4: Write a recursive function to find n factorial. n! = n * (n-1) * (n-2)... 3 * 2 * 1 Factorial(5) = 120 = 5 * 4 * 3 * 2 * 1 Base case: if (n == 1) return 1; General case: n! = n * (n-1) * (n-2)... 3 * 2 * 1 = n * [(n-1) * (n-2)... 3 * 2 * 1] = n * (n-1)! OR: Factorial(n) = n * Factorial(n-1)

10/14/2015cosc237/recursion15 Factorial n! = n x (n-1)! int factorial(int num) { if (num == 0) return num; else return num * Factorial(num – 1); }

16 Recursive Factorial Method (continued)

10/14/2015cosc237/recursion17 Example #5: Write a recursive function to find x n. Base case: 2 0 = 1 General Case: 2 n = 2 * 2 n-1

10/14/2015cosc237/recursion18 power function int Power(int x, int n) // n >0 { if (n == 1) return x; // base case else return x * Power(x,n-1); }

10/14/2015cosc237/recursion19 Power, n<0 Note that 2 -3 = 1/2 3 = 1/8 In general, x n = 1/ x -n for non-zero x, and integer n<0.

10/14/2015cosc237/recursion20 Power float Power (float x, int n) { if (n == 0) // base case return 1; else if (n > 0) // first general case return (x * Power(x, n - 1)); else // second general case return (1.0 / Power(x, - n)); }

10/14/2015cosc237/recursion21 Use the box method to trace Activation record Represent each call to the function during the course of the execution by a new box Local environment

22 Tracing a Recursive Method After completing a recursive call: –Control goes back to the calling environment –Recursive call must execute completely before control goes back to previous call –Execution in previous call begins from point immediately following recursive call

10/14/2015cosc237/recursion23 void mystery(char param1, char param2) { if (param1 != param2) { param1++; param2--; Mystery(param1, param2); System.out.println(param1); System.out.println(param2); } Show all output resulting from the following invocation:mystery('A','G'); Under what circumstances does mystery result in infinite recursion? Exercises

10/14/2015cosc237/recursion24 int TermUnknown (int someInt) // This is a classic number theory problem for which // termination for all input is uncertain. { if (someInt == 1) return 0; if (someInt % 2 == 1) return 1 + TermUnknown(3 * someInt +1); return TermUnknown(someInt/2); } What value does each of the following invocations return? a. TermUnknow(1); b. TermUnknown(4); c. TermUnknown(3);

25 Largest Value in Array public static int largest(int[] list, int lowerIndex, int upperIndex) { int max; if (lowerIndex == upperIndex) return list[lowerIndex]; else { max = largest(list, lowerIndex + 1, upperIndex); if (list[lowerIndex] >= max) return list[lowerIndex]; else return max; }

26 Largest Value in Array (continued)

10/14/2015cosc237/recursion27 Recursive Functions Recursive function - invokes itself directly or indirectly –direct recursion - function is invoked by a statement in its own body –indirect recursion - one function initiates a sequence of function invocations that eventually invokes the original A->B->C->A

10/14/2015cosc237/recursion28 When a function is invoked - activated activation frame - collection of information maintained by the run-time system(environment) –current contents of local automatic variables –current contents of all formal parameters –return address –pushed on stack

29 Linear Search array a two subscripts, low and high Key Return -1 if key is not found in the elements a[low...high]. Otherwise, return the subscript where key is found

30 // Recursive definition int LinearSearch ( /* in */ const int a[ ], /* in */ int low, /* in */ int high, /* in */ int key ) { if ( a [ low ] == key ) // base case return low ; else if ( low == high) // second base case return -1 ; else // general case return LinearSearch( a, low + 1, high, key ) ; } 30

31 Function BinarySearch( ) l BinarySearch that takes sorted array a, and two subscripts, low and high, and a key as arguments. It returns -1 if key is not found in the elements a[low...high], otherwise, it returns the subscript where key is found l BinarySearch can be written using iteration or using recursion

32 // Iterative definition int BinarySearch (int a[ ], int low, int high,int key ) { int mid; while ( low <= high ) { // more to examine mid = (low + high) / 2 ; if ( a [ mid ] == key ) // found at mid return mid ; else if ( key < a [ mid ] ) // search in lower half high = mid - 1 ; else // search in upper half low = mid + 1 ; } return -1 ; // key was not found } 32

33 // Recursive definition int BinarySearch (int a[ ], int low, int high, int key) { int mid = (low + high) / 2 ; if ( low > high ) // base case -- not found return -1; if ( a [ mid ] < key ) // search in upper half return BinarySearch( a, mid + 1, high, key ) ; else if ( key < a [ mid ] ) // search in lower half return BinarySearch ( a, low, mid - 1, key ); else return mid; } 33

10/14/2015cosc237/recursion34 "One Small Step/Complete the Solution" Each invocation of a recursive function performs one small step towards the entire solution and makes a recursive call to complete the solution.

10/14/2015cosc237/recursion35 Recursive Functions Non-value-returning –invoked as separate stand-alone statement value-returning –invoked in an expression –often embedded within return statement

36 Recursion or Iteration? Two ways to solve particular problem: –Iteration or Recursion Every loop can be replaced by recursion not every recursion can be replaced by a loop Iterative control structures use looping to repeat a set of statements Tradeoffs between two options: –Sometimes recursive solution is easier –Recursive solution is often slower

10/14/2015cosc237/recursion37 Factorial(loop version) int LoopFactorial (int n) { int i; int fact = 1; for (i = 1; i <= n; i++) fact = fact * i; return fact; }

10/14/2015cosc237/recursion38 Factorial - table lookup int factorial[8] = {1,1,2,6,24,120,720,5040}; faster, can simplify algorithms more memory space

Java Programming: Program Design Including Data Structures 39 Programming Example: Decimal to Binary public static void decToBin(int num, int base) { if (num > 0) { decToBin(num / base, base); System.out.print(num % base); }

Java Programming: Program Design Including Data Structures 40 Programming Example: Decimal to Binary

10/14/2015cosc237/recursion41 When to Use Recursion If the problem is stated recursively if recursive algorithm is less complex than recursive algorithm if recursive algorithm and nonrecursive algorithm are of similar complexity - nonrecursive is probably more efficient consider table-driven code

10/14/2015cosc237/recursion42 References: [1] Programming and Problem Solving with C++, third edition, by Neal Dale, Chip Weems, and Mark Headington, Jones and Bartlett Publishers, [2] Data Abstraction and Structures Using C++, by Mark R. Headington, and David D. Riley, Jones and Bartlett Publishers, [3] Starting Out with C++, by Tony Gaddis, Scott Jones Publishers, Java Programming: [4] Program Design Including Data Structures, D.S. Malik