Presentation is loading. Please wait.

Presentation is loading. Please wait.

A Computer Science Tapestry 1 Announcements l Midterm 1 is on November 25, 2006, 10:40 – 12:20 l Homework 3 is due November 8, 2006, 21:00 ä Robot application.

Similar presentations


Presentation on theme: "A Computer Science Tapestry 1 Announcements l Midterm 1 is on November 25, 2006, 10:40 – 12:20 l Homework 3 is due November 8, 2006, 21:00 ä Robot application."— Presentation transcript:

1 A Computer Science Tapestry 1 Announcements l Midterm 1 is on November 25, 2006, 10:40 – 12:20 l Homework 3 is due November 8, 2006, 21:00 ä Robot application. I hope you attended recitations before the week. ä Be careful where and how you create the robots Each robot must be created only once within the main Examine example robot programs of previous week recitations ä Scope rules say that each identifier can be used only in the compound block in which it is declared If you receive an “undeclared identifier” error for robots even you declare them, check where you declare and use them! ä One mistake in the sample exe and another mistake in the pdf file are corrected and webct is updated

2 A Computer Science Tapestry 2 In this ppt file l Mostly Sections 4.5 and 4.6 ä Functions that return values ä math library functions ä string as a class string constructors string member functions and string processing ä date class (4.6.3) will be covered later

3 A Computer Science Tapestry 3 Functions that return values Functions we’ve written so far are void functions ä They do some job and returns back, but without a value ä Parameters are used for one-way data transfer into the function to be called ä What can you do to transfer a computed value out of a function? to the main program or to other function (whatever the caller one) ä Parameters that we have seen and used until now are not enough  Void function call is not used in an expression, i.e. no value is associated with a void function Head(); DoThat(); Verse("cow", "moo"); l Non-void functions can return values of any type ä function call becomes an expression when the function finishes, the function call is replaced by the returned value

4 A Computer Science Tapestry 4 Functions that return values Example (see area_func_return.cpp): suppose circlearea function takes the radius as parameter and returns the area. In the program we call circlearea as an expression (you have to use the returned value somewhere) area = circlearea(r); cout << circlearea(12) << endl; if (circlearea(r/2) >= 100) cout << “large circle” << endl; circlearea(r); // syntax ok, but meaningless function call // returned value is not used

5 A Computer Science Tapestry 5 Math library functions l Mathematical functions like square root, logarithm, sin, cos, etc. l prototypes in header file cmath #include l Full list is in page 758 (Table F.1) – partial list is in table 4.5.  correction in Table F.1: int abs (int x) l Note them on your cheat-sheet for the exam Example use of function sqrt ä see usemath.cpp  how did we use sqrt function? in cout as an expression  could we use sqrt in assignment? How? yes, let’s do it.  what happens if value is negative? try and see! we can add some if statements to display an error message in case of negative value

6 A Computer Science Tapestry 6 Anatomy of a function Function to calculate volume of a sphere double SphereVol (double radius) { return 4.0*radius*radius*radius*acos(-1)/3; } l Function heading/prototype shows return type.  return type can be any type (incl. string )  theoretically return type may be Robot too, but in practice Robot class is not designed to be used as the return type you do not see any syntax error, but execution may be problematic. So do not return a Robot from a function l Function body may have several statements in it return statement is used to determine the value returned from function, so the expression after it must be of the return type  Function body should include at least one return statement  The return statement causes the function to exit immediately and to return the value after return  A function can have more than one return statements, but only one is executed when the function is called (see next example) return type function name function body parameters

7 A Computer Science Tapestry 7 Functions can return strings string WeekDay(int day) // precondition: 0<= day <= 6 // postcondition: return "Sunday" for 0, // "Monday" for 1, … "Saturday" for 6 { if (0 == day) return "Sunday"; else if (1 == day) return "Monday"; else if (2 == day) return "Tuesday"; else if (3 == day) return "Wednesday"; else if (4 == day) return "Thursday"; else if (5 == day) return "Friday"; else if (6 == day) return "Saturday"; } l A program piece that uses that function string dayName; int dayNum; cout << " enter day (0-6): " ; cin >> dayNum; dayName = WeekDay(dayNum); Which is/are correct use of WeekDay function? Why? cout << WeekDay(5)<< endl; int j = WeekDay(0); cout << WeekDay(2.1)<< endl; string s = WeekDay(22); WeekDay(3);

8 A Computer Science Tapestry 8 Function documentation l Functions usually have a precondition ä What properties (e.g., of parameters) must be true for function to work as intended? ä If there are no parameters, sometimes no precondition ä Some functions work for every parameter value no precondition l Functions always have a postcondition ä If precondition is satisfied what does the function do? What does the function return?

9 A Computer Science Tapestry 9 Example – Compare cost of pizza sizes l Problem: Calculate and compare price per square inch of large and small size pizzas l Solution  a function, say cost, that takes the pizza radius and price as parameters and returns price per square inch  In the main() input radiuses and prices of large and small pizzas calculate the per square inch costs by calling the cost function display the results on screen compare the unit costs to find out which one is best value l See pizza2.cpp

10 A Computer Science Tapestry 10 Example - When is a year a leap year? l Every year divisible by four is a leap year ä Except years divisible by 100 are not Except years divisible by 400 are l Alternatively: ä Every year divisible by 400 is a leap year ä Otherwise, years divisible by 100 are not leap years ä Otherwise, years divisible by 4 are leap years ä Otherwise, not a leap year l Boolean function bool IsLeapYear(int year); // pre: year > 0 // post: return true if year is a leap year

11 A Computer Science Tapestry 11 Implementation and use of leap year function bool IsLeapYear(int year) // precondition: year > 0 // postcondition: returns true if year is a leap year, else returns false { if (year % 400 == 0) // divisible by 400 { return true; } else if (year % 100 == 0) // divisible by 100 { return false; } else if (year % 4 == 0) // divisible by 4 { return true; } return false; } int main() { int year; cout << "enter a year "; cin >> year; if (IsLeapYear(year)) { cout << year << " has 366 days, it is a leap year" << endl; } else { cout << year << " has 365 days, it is NOT a leap year" << endl; } return 0; } See isleap.cpp

12 A Computer Science Tapestry 12 There’s more than one way l No if/else necessary in the function body bool IsLeapYear(int year) // precondition: year > 0 // post: return true if year is a leap year { return ( year % 400 == 0 ) || ( year % 4 == 0 && year % 100 != 0); } l How does this work? l Is this version more efficient? l Are these two versions different from user perspective?

13 A Computer Science Tapestry 13 Functions that return values from the Robot Class l Robot class has several member functions ä Move, TurnRight and SetColor are void functions ä Robot class also has member functions that return values. Some are below. bool Blocked () ä is the robot blocked? bool FacingEast () ä Is the robot facing east? l See RobotWorld.pdf file for the complete list of those functions.

14 A Computer Science Tapestry 14 Free functions and member functions The functions in are free functions, they aren’t part of a class ä C++ is a hybrid language, some functions belong to a class, others do not ä Java is a pure object-oriented language, every function belongs to a class Similarly, IsLeapYear is also free function l Actually any function that does not operate on an object is free functions However, Move, TurnRight are functions for Robots class ä they are not free, they operate on robots only ä that is why they are called member functions

15 A Computer Science Tapestry 15 string as a class string is a class ä String variables are objects, they’re instances of the class ä A class is a collection having members that have common attributes strings share some properties, but have different values l A string is a sequence of characters ä first char is at position 0 first index is 0 ä last valid index (position of the last character): string’s length -1 l Constructors ä without initialization string mystr, s; ä with initialization string s = " Hello World " ; string otherstring = s; or string otherstring(s); ä You may use functions and operators that return strings in initialization string s = " Hello " + " World " //concatenation operator

16 A Computer Science Tapestry 16 string member functions The function length() returns the number of characters string s = "hello"; int len = s.length(); // value of len is 5 s = "";// s is null string len = s.length(); // value of len is 0 l Member functions are applied to objects using dot notation ä Cannot use length() without an object to apply it to  Not valid int x = length(s);  Not valid int x = string.length()  Valid? double y = sqrt(s.length());

17 A Computer Science Tapestry 17 string member functions int length() // postcondition: returns the number of characters string substr(int pos, int len) // precondition: 0 <= pos, and pos < length of the string object // postcondition: returns substring of len characters beginning at position // pos. Returns as many characters as possible if len is too large, but // causes error if pos is out of range (>= length of the string object) int find(string s) // postcondition: returns first position/index at which substring s begins in // string object– returns string::npos if s does not occur l More details in “how to C” in Tapestry

18 A Computer Science Tapestry 18 Extracting substrings A substring is part of a string, substrings can be extracted from a string using member function substr string s = "theater"; int len = s.length(); // value of len is 7 string t = s.substr(0,3); // t is "the", s is “theater” t = s.substr(1,4); // t is now “heat” s = s.substr(3,3); // s is “ate” t is still “heat” s = “cinema”; t = s.substr(4,8); // t is “ma” t = s.substr(8,2); // run-time error See strdemo.cpp which is a sample program that uses length and substr functions

19 A Computer Science Tapestry 19 Finding substrings within strings: find and rfind String member function find looks for an occurrence of one string (which is a parameter) in another (which is the object string), returns position of start of first occurrence  If no occurrence, then string::npos is returned largest unsigned integer (4,294,967,295) string s = "I am the eggman, he is too"; int k = s.find("I"); // k is 0 k = s.find("he"); // k is 6 k = s.find("egg"); // k is 9 k = s.find("a"); // k is 2 cout << s.find("cat"); // output is 4294967295 k = s.find("cat"); // k is –1 since it is signed rfind is same as find, but searches backwards, returns the last occurrence k = s.rfind("he"); // k is 17 k = s.rfind("egg"); // k is 9 See strfind.cpp which is a sample program on find function

20 A Computer Science Tapestry 20 More on strings l You can append one string to the end of another  using operator + string s = "cs201"; s = s + " is easy"; // s is now "cs201 is easy" You can change or extract one character of a string using at member function ä parameter of at must be between 0 and string’s length - 1, otherwise a run-time error occurs string s = "Hello World"; s.at(4) = '!'; // s is now "Hell! World" cout << s.at(1); // displays e on screen s.at(20) = 'a'; //run-time error

21 A Computer Science Tapestry 21 More on strings l We already know how to compare strings l See “How to C” insert and replace functions l String functions and operators we have seen so far are from standard C++ library l Tapestry also has some classes and utility functions ä we will see and use them in time l strutils.h and strutils.cpp ä Tapestry string utilities ä include strutils.h at the beginning of the program ä add strutils.cpp to your project ä see “How to G” (page 776)

22 A Computer Science Tapestry 22 Example (See stringremove.cpp) l Write a function that takes two string parameters (say s1 and s2). Function removes first occurrence of s2 in s1 and returns the resulting string. ä In the main program, test the function by removing some input strings from “Today is Monday” string remove(string s1, string s2) // post: removes first occurrence of s2 from s1 and returns the // resulting string. Returns s1 if s2 does not occur any. { unsigned int location; location = s1.find(s2); if (location != string::npos) { return s1.substr(0, location) + s1.substr(location+s2.length(), s1.length()); } return s1; }

23 A Computer Science Tapestry 23 The class Date l A Tapestry class l we will see later


Download ppt "A Computer Science Tapestry 1 Announcements l Midterm 1 is on November 25, 2006, 10:40 – 12:20 l Homework 3 is due November 8, 2006, 21:00 ä Robot application."

Similar presentations


Ads by Google