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.

Slides:



Advertisements
Similar presentations
© Janice Regan, CMPT 102, Sept CMPT 102 Introduction to Scientific Computer Programming Recursion.
Advertisements

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.
Computer Science 1620 Loops.
Scott Grissom, copyright 2004 Chapter 5 Slide 1 Analysis of Algorithms (Ch 5) Chapter 5 focuses on: algorithm analysis searching algorithms sorting algorithms.
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 Chapter 7. Chapter 7: Recursion2 Chapter Objectives To understand how to think recursively To learn how to trace a recursive method To learn.
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.
Chapter 13 Recursion. Topics Simple Recursion Recursion with a Return Value Recursion with Two Base Cases Binary Search Revisited Animation Using Recursion.
1 Storage Classes, Scope, and Recursion Lecture 6.
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.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. C How To Program - 4th edition Deitels Class 05 University.
Chapter 11Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 11 l Basics of Recursion l Programming with Recursion Recursion.
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.
1 Recursion. 2 Chapter 15 Topics  Meaning of Recursion  Base Case and General Case in Recursive Function Definitions  Writing Recursive Functions with.
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.
Chapter 4 Recursion. Copyright © 2004 Pearson Addison-Wesley. All rights reserved.1-2 Chapter Objectives Explain the underlying concepts of recursion.
Recursion Part 3 CS221 – 2/27/09. Recursion A function calls itself directly: Test() { … Test(); … }
Announcements HW3 grades will be announced this week HW4 is due this week Final exam on August 25, 2010, Wednesday at 09:00 Duration is about 140 minutes.
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.
CPS120: Introduction to Computer Science Functions.
Current Assignments Homework 2 is available and is due in three days (June 19th). Project 1 due in 6 days (June 23 rd ) Write a binomial root solver using.
CPS120: Introduction to Computer Science Lecture 14 Functions.
Java Programming: Guided Learning with Early Objects Chapter 11 Recursion.
CS161 Topic #16 1 Today in CS161 Lecture #16 Prepare for the Final Reviewing all Topics this term Variables If Statements Loops (do while, while, for)
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.
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.
1 Lecture 3 Part 2 Storage Classes, Scope, and Recursion.
© 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.
Extra Recitations Wednesday 19:40-22:30 FENS L055 (tomorrow!) Friday 13:40-16:30 FENS L063 Friday 17: :30 FENS L045 Friday 19:40-22:30 FENS G032.
Searching CSE 103 Lecture 20 Wednesday, October 16, 2002 prepared by Doug Hogan.
Instructor: Alexander Stoytchev CprE 185: Intro to Problem Solving (using C)
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.
Lecture 7 – Repetition (Loop) FTMK, UTeM – Sem /2014.
CS 116 Object Oriented Programming II Lecture 13 Acknowledgement: Contains materials provided by George Koutsogiannakis and Matt Bauer.
CPS Today’s topics Programming Recursion Invariants Reading Great Ideas, p Brookshear, Section Upcoming Copyrights, patents, and.
Recursion.
Recursion: The Mirrors
Solving Problems Recursively
Introduction to Pointers and Dynamic Memory Allocation
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
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.
Chapter 12 Recursion (methods calling themselves)
Announcements Final Exam on August 19th Saturday at 16:00.
Computing Fundamentals
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 Announcements l Please complete the Course Evaluations l Final exam on December 24, 2015, Thursday ä at 16:00 (more info and exam places will be announced via ) ä Duration is about 140 minutes (+/- 10 minutes) ä Comprehensive but last topics will have more weight ä two pages of cheat notes are allowed l HW7 is assigned ä Due Wednesday December 16, at 19:00. ä A sample from previous week recitations will be repeated this week. There will also be new samples from this week topics. ä Number of teams Cannot input or make an assumption on the number of teams to create the vector accordingly ä Run-time errors Mostly due to passing file streams (input or output) to function as value Another reason would be trying to reach a vector element that does not exist. Need to debug and understand the place of the error

A Computer Science Tapestry 2 Recursion, Scope l Not so related to each other l From Chapter 10 ä 10.1, 10.3 (skip ), 10.4

A Computer Science Tapestry 3 Global Variables (10.4.1) l Have you ever need a variable that can be referred in all functions? l Global variables are defined outside of function bodies and can be used in all functions ä but in that cpp file, cannot be used in other cpp files ä Actually there is a way of using a global variable defined in one file to be accessed by another, but it is the topic of CS204. l Global definitions can be shadowed by local definition ä if a global variable is redefined in a function, in that function local one is used, global one cannot be reached l See globaldemo.cpp (not in the book) l Do not use global variables in your homework, but you have to know what they are!

A Computer Science Tapestry 4 Hidden Identifiers (10.4.2) l These are Identifiers defined in inner compound blocks ä An identifier defined in a block can be used only in this block l See scope.cpp as an example l Same identifier names can be used in nested blocks ä shadow rules apply l When an identifier is used, the nearest definition in the same or outer compound blocks is referred ä better to see in an example (scope.cpp) let’s trace that program l Global identifiers and identifiers defined in compound blocks can be used together in more complex cases ä See this week recitations for an example

A Computer Science Tapestry 5 Recursion (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!

A Computer Science Tapestry 6 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 7 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 8 Exponentiation l Computing x n means multiplying n numbers ä x.x.x.x.x.x... x (n times) ä In the function multiply only once, and 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 9 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 10 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 a * semi * semi; } l Study the code in

A Computer Science Tapestry 11 Classic examples of recursion l 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

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

A Computer Science Tapestry 13 Fibonacci Numbers l 1, 1, 2, 3, 5, 8, 13, 21, … l Find n th 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 14 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 15 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 16 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 (see next slide).

A Computer Science Tapestry 17 Example Program for static variables (staticdemo.cpp – not in the book) l Without static variable l With static variable void increment () { int a = 0; a++; cout << a << " "; } for (i=1; i<=5; i++) increment(); Output Each time the function is called variable a is re-initialized to 0 void increment_static () { static int a = 0; a++; cout << a << " "; } for (i=1; i<=5; i++) increment_static(); Output Each time the function is called variable a is NOT re-initialized to 0; it continues from the value of previous call. Initialization is done only in first call

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

A Computer Science Tapestry 19 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); }

A Computer Science Tapestry 20 End of CS 201 Recitations by İnanç Arın, Stefan Rabiger, Omid Kazemy, Deniz Marlalı, Figen Beken Fikri, Yusuf İzmirlioğlu, Gizem Gezici, Saad Sajid Hashmi, Sezen Yağmur Günay, Laleh Eskandarian, Baturay Özgürün, Onur Veyisoğlu, Mustafa Kemal Taş, Begüm Özemek Recitation material prepared by İnanç Arın, Albert Levi Homework graded by Stefan Rabiger, Figen Beken Fikri, Omid Kazemy, Damla Arifoğlu Homework prepared by İnanç Arın, Albert Levi Organizational assistant Laleh Eskandarian Exams prepared by Albert Levi Exams graded by Stefan Rabiger, Figen Beken Fikri, Omid Kazemy, Yusuf İzmirlioğlu, Baturay Özgürün, Deniz Marlalı, Gizem Gezici, Saad Sajid Hashmi, Sezen Yağmur Günay, Laleh Eskandarian, Damla Arifoğlu Extra recitation support Emir Artar Extra office hour support Eralp Şahin, Begüm Benel, Ardıç Sönmez, Burak Dinçer, Bora Makar, Doğancan Uluğ Lectures by Albert Levi Thanks to Gülşen Demiröz, Berrin Yanıkoğlu, Ersin Karabudak, Owen Astrachan, and all previous years’ CS201 assistants Special thanks to all of you for your time and effort in this course Good Luck in the final exam Copyright © 2015, Sabanci University