240 likes | 264 Views
In this ppt file. 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. Functions that return values.
E N D
In this ppt file • 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
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 • 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 • In this way, values computed in functions can be transferred into the caller functions • Void function call is not used in an expression, i.e. no value is associated with a void function Head(); DoThat(); Verse("cow", "moo");
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
Math library functions • Mathematical functions like square root, logarithm, sin, cos, etc. • prototypes in header file cmath #include <cmath> • 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) • Note these math library functions 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
Anatomy of a function function name return type Function to calculate volume of a sphere double SphereVol (double radius) { return 4.0*radius*radius*radius*acos(-1)/3; } • 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 • Function body may have local variables and several statements in it • return statement is used to determine the value returned fromfunction, so the expression after it must be of the return type • Function body should include at least onereturnstatement • 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) parameters function body
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"; } 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); Functions can return strings See weekday.cpp
Function documentation • 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, then no precondition • Some functions work for every parameter value • no precondition • Functions always have a postcondition • If precondition is satisfied what does the function do? What does the function return? • Preconditions and Posconditions are written as comments at the beginning of functions • good programming style
Example – Compare cost of pizza sizes • Problem: Calculate and compare price per square inch of large and small size pizzas • Solution • a function, say cost, that takes the pizza radius and price as parameters and returns price per square inch • In main() • input radiuses and prices of large and small pizzas • calculate the per square inch costs by calling the cost function twice • display the results on screen • compare the unit costs to find out which one is best value • See pizza2.cpp
Example - When is a year a leap year? • Every year divisible by four is a leap year • Except years divisible by 100, which are not lear years (e.g. 1700, 1800, 1900 were not leap years) • Except years divisible by 400, which are leap years (e.g. 2000 was leap year) • 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 • Boolean function bool IsLeapYear(int year); // pre: year > 0 // post: return true if year is a leap year
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
There’s more than one way • 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 % 100 != 0 &&year % 4 == 0); } • How does this work? • Is this version more efficient? • Are these two versions different from user perspective?
Functions that return values from the Robot Class • 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? • See RobotWorld.pdf file for the complete list of those functions.
Free functions and member functions • The functions in <cmath> are free functions, they aren’t part of a class • C++ is a hybrid language, some functions belong to a class, some others do not • Java and C# are pure object-oriented languages; every function belongs to a class • Similarly, IsLeapYear is also free function • Actually any function that does not operate on an object is a free function • However, Move, TurnRight are functions for Robot class • they are not free, they operate on robots only • that is why they are called member functions • All robot functions are member functions of robot class
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 • 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 • Constructors • without initialization. In this case empty string (a string with no characters in it) is generated 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
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 (empty) string len = s.length(); // value of len is 0 • 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());
string member functions unsigned int length() // postcondition: returns the number of characters string substr(unsigned 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) unsigned 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 • More details in “how to C” in Tapestry (our textbook)
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
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 unsigned int z; z = s.find("cat"); // zhas the value of string::npos 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
find and rfindwith 2 parameters • There is another version of find and rfind that takes two parameters • First parameter is still a string (the search string) • Second parameter is an integer (an index value) • In this version, searching starts from the character for which the index is the second parameter of find or rfind • Useful when you need to search a string not from the beginning or endpoint, but from somewhere in the middle string s = "I am the eggman, he is too"; int k; k = s.find("a"); // k is 2 k = s.find("a",5); // k is 13 k = s.rfind("he"); // k is 17 k = s.rfind("he", 15); // k is 6
More on strings • 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
Example (See stringremove.cpp) • 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; }
More on strings • We already know how to compare strings • See “How to C” • insert and replace functions • String functions and operators we have seen so far are from standard C++ library • Tapestry also has some classes and utility functions • we will see and use them in time • 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) for these utility functions
The class Date • A Tapestry class • we will see later