A Computer Science Tapestry 1 Recursion (Tapestry 10.1, 10.3) l Recursion is an indispensable technique in a programming language ä Allows many complex.

Slides:



Advertisements
Similar presentations
Introduction to Recursion and Recursive Algorithms
Advertisements

© Janice Regan, CMPT 102, Sept CMPT 102 Introduction to Scientific Computer Programming Recursion.
Recursion. Recursive Definitions A recursive definition is one which uses the word being defined in the definition Not always useful:  for example, in.
Lesson 19 Recursion CS1 -- John Cole1. Recursion 1. (n) The act of cursing again. 2. see recursion 3. The concept of functions which can call themselves.
 Monday, 9/30/02, Slide #1 CS106 Introduction to CS1 Monday, 9/30/02  QUESTIONS (on HW02, etc.)??  Today: Libraries, program design  More on Functions!
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 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.
Department of Computer Science and Engineering, HKUST 1 HKUST Summer Programming Course 2008 Recursion.
Recursion Chapter Nature of Recursion t Problems that lend themselves to a recursive solution have the following characteristics: –One or more.
Chapter 2 Recursion: The Mirrors CS Data Structures Mehmet H Gunes Modified from authors’ slides.
What is recursion? Imagine checking the dictionary for “apple”  a round fruit with a firm white flesh and a green, red or yellow skin  the usually sweet-tasting.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 12: Recursion Problem Solving, Abstraction, and Design using C++
CompSci 100E 10.1 Solving Problems Recursively  Recursion is an indispensable tool in a programmer’s toolkit  Allows many complex problems to be solved.
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.
Chapter 11Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 11 l Basics of Recursion l Programming with Recursion Recursion.
Chapter 12 Recursion, Complexity, and Searching and Sorting
Lecturer: Dr. AJ Bieszczad Chapter 11 COMP 150: Introduction to Object-Oriented Programming 11-1 l Basics of Recursion l Programming with Recursion Recursion.
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.
CPS 100, Spring From Recursion to Self Reference public int calc(int n){ return n*calc(n-1); } l What is the Internet?  A network of networks.
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 Joe Meehean.  call themselves directly  or indirectly void f(){... f();... } void g(){... h();... } void h(){... g();... }
CompSci 100E 12.1 Solving Problems Recursively  Recursion is an indispensable tool in a programmer’s toolkit  Allows many complex problems to be solved.
Chapter 13 Recursion. Learning Objectives Recursive void Functions – Tracing recursive calls – Infinite recursion, overflows Recursive Functions that.
1 TCSS 143, Autumn 2004 Lecture Notes Recursion Koffman/Wolfgang Ch. 7, pp ,
Recursion Part 3 CS221 – 2/27/09. Recursion A function calls itself directly: Test() { … Test(); … }
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.
CompSci 100e 6.1 Hashing: Log ( ) is a big number l Comparison based searches are too slow for lots of data  How many comparisons needed for a.
Recursion. What is recursion? Rules of recursion Mathematical induction The Fibonacci sequence Summary Outline.
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.
CPS 100, Spring Tools: Solve Computational Problems l Algorithmic techniques  Brute-force/exhaustive, greedy algorithms, dynamic programming,
Chapter 11Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 11 l Basics of Recursion l Programming with Recursion Recursion.
© 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.
A Computer Science Tapestry 10.1 Solving Problems Recursively l Recursion is an indispensable tool in a programmer’s toolkit  Allows many complex problems.
CompSci Review of Recursion with Big-Oh  Recursion is an indispensable tool in a programmer’s toolkit  Allows many complex problems to be solved.
© Janice Regan, CMPT 128, February CMPT 128: Introduction to Computing Science for Engineering Students Recursion.
Recursion Fundamentals of Recursion l Base case (aka exit case)  Simple case that can be solved with no further computation  Does not make a recursive.
Searching CSE 103 Lecture 20 Wednesday, October 16, 2002 prepared by Doug Hogan.
CS162 - Topic #10 Lecture: Recursion –The Nature of Recursion –Tracing a Recursive Function –Work through Examples of Recursion Programming Project –Discuss.
A Computer Science Tapestry 10.1 Solving Problems Recursively l Recursion is an indispensable tool in a programmer’s toolkit ä Allows many complex problems.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 14 Recursion.
CS 116 Object Oriented Programming II Lecture 13 Acknowledgement: Contains materials provided by George Koutsogiannakis and Matt Bauer.
A Computer Science Tapestry 1 Announcements l Please complete the Course Evaluations l Final exam on December 24, 2015, Thursday ä at 16:00 (more info.
CPS Today’s topics Programming Recursion Invariants Reading Great Ideas, p Brookshear, Section Upcoming Copyrights, patents, and.
Welcome to Recursion! Say what?!? Recursion is… the process of solving large problems by simplifying them into smaller ones. similar to processing using.
Chapter 13 Recursion Copyright © 2016 Pearson, Inc. All rights reserved.
Recursion DRILL: Please take out your notes on Recursion
Plan for the Week Review for Midterm Source code provided
Solving Problems Recursively
Recursive Thinking Chapter 9 introduces the technique of recursive programming. As you have seen, recursive programming involves spotting smaller occurrences.
Chapter 14 Recursion. Chapter 14 Recursion Overview 14.1 Recursive Functions for Tasks 14.2 Recursive Functions for Values 14.3 Thinking Recursively.
Announcements Final Exam on August 17th Wednesday at 16:00.
Recursive Thinking Chapter 9 introduces the technique of recursive programming. As you have seen, recursive programming involves spotting smaller occurrences.
Recursion "To understand recursion, one must first understand recursion." -Stephen Hawking.
Announcements Final Exam on August 19th Saturday at 16:00.
Cs212: DataStructures Computer Science Department Lab 3 : Recursion.
Announcements Final Exam on December 25th Monday at 16:00.
Basics of Recursion Programming with Recursion
Announcements HW3 grades will be announced this week
Chapter 18 Recursion.
Solving Problems Recursively
Recursive Algorithms 1 Building a Ruler: drawRuler()
Chapter 13 Recursion Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
Solving Problems Recursively
Presentation transcript:

A Computer Science Tapestry 1 Recursion (Tapestry 10.1, 10.3) l Recursion is an indispensable technique in a programming language ä Allows many complex problems to be solved simply ä Elegance and understanding in code often leads to better programs: easier to modify, extend, verify ä Sometimes recursion isn’t appropriate. When it performs bad, it can be very bad! ä need knowledge and experience in how to use it. Some programmers are “recursion” programmers, some are not I think I am not  l Recursion is not a statement, it is a technique! l The basic idea is to get help solving a problem from coworkers (clones) who work and act like you do ä Ask clone to solve a simpler but similar problem ä Use clone’s result to put together your answer ä looks like calling a function in itself, but should be done very carefully! l Actually recursion has been covered in CS201; now an overview will be given since we are going to use it.

A Computer Science Tapestry 2 Print words entered, but backwards l Can use a vector, store all the words and print in reverse order ä Using a vector is probably the best approach, but recursion works too (see printreversed.cpp) void PrintReversed() { string word; if (cin >> word) // reading succeeded? { PrintReversed(); // print the rest reversed cout << word << endl; // then print the word } int main() { PrintReversed(); return 0; } The function PrintReversed reads a word, prints the word only after the clones finish printing in reverse order  Each clone runs a copy of the function, and has its own word variable l See the trace on the board

A Computer Science Tapestry 3 What is recursion? l Not exactly calling a function in itself ä although it seems like this l Recursion is calling a “copy” of a function in itself ä clone l All local identifiers are declared anew in a clone ä when execution order comes back to the caller clone, the values in that clone is used

A Computer Science Tapestry 4 Exponentiation l Computing x n means multiplying n numbers ä x.x.x.x.x.x... x (n times) ä If you want to multiply only once, you ask a clone to multiply the rest (x n = x.x n-1 ) clone recursively asks other clones the same until no more multiplications each clone collects the results returned, do its multiplication and returns the result l See the trace on board double Power(double x, int n) // post: returns x^n { if (n == 0) { return 1.0; } return x * Power(x, n-1); }

A Computer Science Tapestry 5 General Rules of Recursion l Although we don’t use while, for statements, there is a kind of loop here ä if you are not careful enough, you may end up infinite recursion l Recursive functions have two main parts ä There is a base case, sometimes called the exit case, which does not make a recursive call printreversed: having no more input exponentiation: having a power of zero ä All other cases make a recursive call, most of the time with some parameter that moves towards the base case Ensure that sequence of calls eventually reaches the base case ä we generally use if - else statements to check the base case not a rule, but a loop statement is generally not used in a recursive function

A Computer Science Tapestry 6 Factorial (recursive) BigInt RecFactorial(int num) { if (0 == num) { return 1; } else { return num * RecFactorial(num - 1); } l See Tapestry (facttest.cpp) to determine which version (iterative or recursive) performs better? ä almost the same

A Computer Science Tapestry 7 Fibonacci Numbers l 1, 1, 2, 3, 5, 8, 13, 21, … l Find nth fibonacci number ä see fibtest.cpp for both recursive and iterative functions and their timings l Recursion performs very bad for fibonacci numbers ä reasons in the next slide

A Computer Science Tapestry 8 Fibonacci: Don’t do this recursively int RecFib(int n) // precondition: 0 <= n // postcondition: returns the n-th Fibonacci number { if (0 == n || 1 == n) { return 1; } else { return RecFib(n-1) + RecFib(n-2); } l Too many unncessary calls to calculate the same values ä How many for 1? ä How many for 2, 3?

A Computer Science Tapestry 9 What’s better: recursion/iteration? l There’s no single answer, many factors contribute ä Ease of developing code ä Efficiency l In some examples, like Fibonacci numbers, recursive solution does extra work, we’d like to avoid the extra work ä Iterative solution is efficient ä The recursive inefficiency of “extra work” can be fixed if we remember intermediate solutions: static variables l Static variable: maintain value over all function calls ä Ordinary local variables constructed each time function called ä but remembers the value from previous call ä initialized only once in the first function call

A Computer Science Tapestry 10 Fixing recursive Fibonacci int RecFibFixed(int n) // precondition: 0 <= n <= 30 // postcondition: returns the n-th Fibonacci number { static vector storage(31,0); if (0 == n || 1 == n) return 1; else if (storage[n] != 0) return storage[n]; else { storage[n] = RecFibFixed(n-1) + RecFibFixed(n-2); return storage[n]; } l Storage keeps the Fibonacci numbers calculated so far, so that when we need a previously calculated Fibonacci number, we do not need to calculate it over and over again. l Static variables initialized when the function is called for the first time ä Maintain values over calls, not reset or re-initialized in the declaration line ä but its value may change after the declaration line. l Not only vectors, variables of any types can be static.

A Computer Science Tapestry 11 Recursive Binary Search l Binary search is good for searching an entry in sorted arrays/vectors l Recursive solution  if low is larger than high not found ä if mid-element is the searched one return mid (found)  if searched element is higher than the mid element search the upper half by calling the clone for the upper half  if searched element is lower than the mid element search the lower half by calling the clone for the lower half Need to add low and high as parameters to the function

A Computer Science Tapestry 12 Recursive Binary Search int bsearchrec(const vector & list, const string& key, int low, int high) // precondition: list.size() == # elements in list // postcondition: returns index of key in list, -1 if key not found { int mid; // middle of current range if (low > high) return -1; //not found else { mid = (low + high)/2; if (list[mid] == key) // found key { return mid; } else if (list[mid] < key) // key in upper half { return bsearchrec(list, key, mid+1, high); } else // key in lower half { return bsearchrec(list, key, low, mid-1); }