Announcements Final Exam on August 17th Wednesday at 16:00.

Slides:



Advertisements
Similar presentations
Towers of Hanoi Move n (4) disks from pole A to pole C such that a disk is never put on a smaller disk A BC ABC.
Advertisements

Recursion Ellen Walker CPSC 201 Data Structures Hiram College.
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.
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.
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.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 12: Recursion Problem Solving, Abstraction, and Design using C++
A Computer Science Tapestry 1 Recursion (Tapestry 10.1, 10.3) l Recursion is an indispensable technique in a programming language ä Allows many complex.
Recursion.
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 02 Recursion Compiled by: Dr. Mohammad Omar Alhawarat.
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.
Chapter 8 Recursion Modified.
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.
Recursion Part 3 CS221 – 2/27/09. Recursion A function calls itself directly: Test() { … Test(); … }
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.
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.
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.
A Computer Science Tapestry 10.1 Solving Problems Recursively l Recursion is an indispensable tool in a programmer’s toolkit ä Allows many complex problems.
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.
Recursion Chapter 2 Objectives Upon completion you will be able to:
Recursion Powerful Tool
Recursion.
Recursion.
Chapter 13 Recursion Copyright © 2016 Pearson, Inc. All rights reserved.
Chapter 19: Recursion.
Recursion Version 1.0.
Chapter 10 Recursion Instructor: Yuksel / Demirer.
Recursion DRILL: Please take out your notes on Recursion
Recursion: The Mirrors
Plan for the Week Review for Midterm Source code provided
Chapter 17 Recursion.
Solving Problems Recursively
Recursion Chapter 12.
Recursive Thinking Chapter 9 introduces the technique of recursive programming. As you have seen, recursive programming involves spotting smaller occurrences.
Java Software Structures: John Lewis & Joseph Chase
Chapter 14 Recursion. Chapter 14 Recursion Overview 14.1 Recursive Functions for Tasks 14.2 Recursive Functions for Values 14.3 Thinking Recursively.
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.
Recursive Definitions
Chapter 12 Recursion (methods calling themselves)
Recursion Chapter 11.
Announcements Final Exam on August 19th Saturday at 16:00.
Chapter 17 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:

Announcements Final Exam on August 17th Wednesday at 16:00. This week recitations, we will solve sample final questions. I will also send previous years’ exams via email. Extra Recitations (Time and Locations to be Announced) 15 August Monday 16 August Tuesday 17 August Wednesday Final Classrooms: if (true)  cout << " FENS G077 " << endl;

Recursion (10.1, 10.3) Recursion is an essential 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. Recursion is not a statement, it is a technique! 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!

Print words entered, but backwards 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 See the trace on the board

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

Exponentiation Computing xn 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 (xn = x.xn-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 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);

General Rules of Recursion 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 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

Faster exponentiation double Power(double a, int n) // post: returns a^n { if (n == 0) { return 1.0; } double semi = Power(a, n/2); if (n % 2 == 0) { return (semi * semi); return Power(a, n/2) * Power(a, n/2); return (a * semi * semi); Study the code in 10.1.2

Classic examples of recursion For some reason, computer science uses these examples: Factorial: we have seen the loop version, now we will see the recursive one Fibonacci numbers: Classic example of bad recursion (will see) Towers of Hanoi (will not cover) N disks on one of three pegs, transfer all disks to another peg, never put a disk on a smaller one, only on larger Peg#1 #2 #3

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

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

Fibonacci: Don’t do this recursively 5 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); Too many unnecessary calls to calculate the same values How many for 1? How many for 2, 3? 4 3 3 2 2 1 2 1 1 1 1

What’s better: recursion/iteration? There’s no single answer, many factors contribute Ease of developing code Efficiency 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 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

Fixing recursive Fibonacci int RecFibFixed(int n) // precondition: 0 <= n <= 30 // postcondition: returns the n-th Fibonacci number { static vector<int> 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]; } 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. 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.

Recursive Binary Search Binary search is good for searching an entry in sorted arrays/vectors We have seen the iterative approach before Now 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

Recursive Binary Search int bsearchrec(const vector<string>& 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);