Download presentation
Presentation is loading. Please wait.
Published byDonna Whitehead Modified over 8 years ago
1
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 email) ä 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
2
A Computer Science Tapestry 2 Recursion, Scope l Not so related to each other l From Chapter 10 ä 10.1, 10.3 (skip 10.3.3), 10.4
3
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!
4
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
5
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!
6
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
7
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
8
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); }
9
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
10
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 10.1.2
11
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
12
A Computer Science Tapestry 12 Factorial (recursive) BigInt RecFactorial(int num) { if (0 == num) { return 1; } else { return num * RecFactorial(num - 1); } l See 10.3.1 (facttest.cpp) to determine which version (iterative or recursive) performs better? ä almost the same, but iterative is a bit better
13
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
14
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? 5 4 32 3 2 0 2 1 1 1 0 1 01
15
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
16
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).
17
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 1 1 1 1 1 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 1 2 3 4 5 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
18
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
19
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); }
20
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
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.