1 / 50

COMS 261 Computer Science I

COMS 261 Computer Science I. Title: String Class Date: October 7, 2005 Lecture Number: 16. Announcements. Homework Exercises: 5.9, 5.10, 5.11, 5.22, 5.25 Due Friday, 10/14/05 Project 1 Pig Latin Translator 5.41 Due Friday, 10/14/05. Review. Functions Libraries Prototypes

kirsi
Download Presentation

COMS 261 Computer Science I

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. COMS 261Computer Science I Title: String Class Date: October 7, 2005 Lecture Number: 16

  2. Announcements • Homework • Exercises: 5.9, 5.10, 5.11, 5.22, 5.25 • Due Friday, 10/14/05 • Project 1 • Pig Latin Translator • 5.41 • Due Friday, 10/14/05

  3. Review • Functions • Libraries • Prototypes • Header files • Strings

  4. Outline • Strings • Function

  5. C++ Strings • Strings are useful in manipulating chunks of text • Must include the string header file • #include <string> • A string is a class or an object • Data members • Member functions

  6. C++ Strings • Define a string • string myStr; • string myStr = “look at the cute doggie”; • string myStr(“look at the cute doggie”); • Utilize member functions • int length = myStr.size() • string myOtherStr = myStr.substr(5, 7); • In general • stringVariable.operation(parameters);

  7. C++ Strings • Strings representation • An array of characters • Each character can be indexed or accessed • String myStr(“Da Boss”); • The subscript operator [ ] is used to access the characters D <= myStr[0] myStr D a B o s s index 0 1 2 3 4 5 6

  8. C++ Strings #include <iostream> #include <string> using namespace std; int main() { string myStr("The dog"); for (int i = 0; i < myStr.size(); i++) { cout << "myStr[" << i << "]: " << myStr[i] << endl; } return 0; }

  9. C++ Strings • Other member functions • compare: • For sorting in alphabetic order • string myName = “Prof. P”; • string yourName = “Prof. V”; • int val = myName.compare(yourName); • val < 0 means myName is < yourName • val == 0 means myName is == yourName • val > 0 means myName is > yourName

  10. C++ Strings • Other member functions • The assignment operator (=) • string grade = “A”; • grade = “C”; • append(string) • string myStr = “Prof. P”; • string myStr.append(“ Hemler”);

  11. C++ Strings • Other member functions • find(char) • Return the index of the first occurrence of char on the string • -1 if the character is not found • Compound assignment statement • += (append or concatenate)

  12. Functions • At this junction, • I’d like to start talkin about the function

  13. Execution Process • Function body of invoked function is executed • Flow of control then returns to the invocation statement • The return value of the invoked function is used as the value of the invocation expression

  14. Function Prototypes • Before a function can appear in an invocation its interface must be specified • Prototype or complete definition int Max(int a, int b)

  15. Function Definition • Includes description of the interface and the function body • Interface • Similar to a function prototype, but parameters’ names are required • Body • Statement list with curly braces that comprises its actions • Return statement to indicate value of invocation

  16. Function name Formal parameter Return type Local object definition Function body Return statement Function Definition float circleArea (float r) { const float Pi = 3.1415; return Pi * r * r; }

  17. Actual parameter To process the invocation, the function that contains the insertion statement is suspended and circleArea() does its job. The insertion operator is then completed using the value supplied by circleArea(). Function Invocation cout << circleArea(MyRadius) << endl;

  18. Simple Programs • Single file • Include statements • Using statements • Function prototypes • Function definitions • Functions use value parameter passing • Also known as pass by value or call by value • The actual parameter is evaluated and a copy is given to the invoked function

  19. #include <iostream> using namespace std; float CircleArea(float r); // main(): manage circle computation int main() { cout << "Enter radius: "; float MyRadius; cin >> MyRadius; float Area = CircleArea(MyRadius); cout << "Circle has area " << Area; return 0; } // CircleArea(): compute area of radius r circle float CircleArea(float r) { const float Pi = 3.1415; return Pi * r * r; }

  20. Value Parameter Rules • Formal parameter • Created on function invocation • Initialized with value of the actual parameter • Changes to formal parameter do not affect actual parameter • Reference to a formal parameter produces the value for it in the current activation record • New activation record for every function invocation

  21. Value Parameter Rules • Formal parameter • Formal parameter name is only known within its function • Formal parameter ceases to exist when the function completes • Activation record memory is automatically released at function completion

  22. PromptAndRead() // promptAndRead(): prompt and extract next // integer int promptAndRead() { cout << "Enter number (integer): "; int Response; cin >> Response; return Response; }

  23. Sum() // pum(): compute sum of integers in a ... b int sum(int a, int b) { int total = 0; for (int i = a; i <= b; ++i) { total += i; } return total; }

  24. Problem • Definition • Input two numbers representing a range of integers and compute and display the sum of the integers that lie in that range

  25. Problem • Design • Prompt user and read the first number • Prompt user and read the second number • Calculate the sum of integers in the range smaller...larger by adding in turn each integer in that range • Display the sum

  26. Range.cpp #include <iostream> using namespace std; int promptAndRead(); int sum(int a, int b); int main() { int firstNumber = promptAndRead(); int secondNumber = promptAndRead(); int rangeSum = sum(firstNumber , secondNumber); cout << "The sum from " << firstNumber << " to " << secondNumber << " is " << rangeSum << endl; return 0; }

  27. Range.cpp // promptAndRead(): prompt & extract next integer int promptAndRead() { cout << "Enter number (integer): "; int Response; cin >> Response; return Response; } // sum(): compute sum of integers in a ... b int sum(int a, int b) { int total = 0; for (int i = a; i <= b; ++i) { total += i; } return total; }

  28. Blocks and Local Scope • A block is a list of statements within curly braces { . . . }

  29. Blocks and Local Scope • Blocks can be put anywhere a statement can be put • Blocks within blocks are nested blocks { { . . . } } Block is nested within another block

  30. Local Object Manipulation void f() { int i = 1; cout << i << endl; // insert 1 { int j = 10; cout << i << j << endl; // insert 1 10 i = 2; cout << i << j << endl // insert 2 10 } cout << i << endl; // insert 2 cout << j << endl; // illegal }

  31. Name Reuse • A nested block can define an object with the same name as an enclosing block • The new definition is in effect in the nested block

  32. Don’t Do This At Home void f() { { int i = 1; cout << i << endl; // insert 1 { cout << i << endl; // insert 1 char i = 'a'; cout << i << endl; // insert a } cout << i << endl; // insert 1 } cout << i << endl; // illegal insert }

  33. Global Scope • Objects not defined within a block are global objects • A global object can be used by any function in the file that is defined after the global object • It is best to avoid programmer-defined global objects • Exceptions tend to be important constants

  34. Global Scope • Global objects with appropriate declarations can even be used in other program files • cout, cin, and cerr are global objects that are defined in by the iostream library • Local objects can reuse a global object's name • Unary scope operator :: can provide access to global object even if name reuse has occurred

  35. Don’t Do This At Home Either int i = 1; int main() { cout << i << endl; // insert 1 { char i = 'a'; cout << i << endl; // insert a ::i = 2; cout << i << endl; // insert a cout << ::i << endl; // insert 2 } cout << i << endl; return 0; }

  36. Consider int main() { int number1 = promptAndRead(); int number2 = promptAndRead(); if (number1 > number2) { Swap(number1, number2); } cout << "The numbers in sorted order:" << number1 << ", " << number2 << endl; return 0; }

  37. Using Formal Parameters void swap(int a, int b) { int temp = a; a = b; b = temp; return; }

  38. Using Formal Parameters Code does NOT do what we want

  39. Consider • A parameter passing style where • Changes to the formal parameter change the actual parameter

  40. That would work!

  41. Reference Parameters • If the formal argument declaration is a reference parameter then • Formal parameter becomes an alias for the actual parameter • Changes to the formal parameter change the actual parameter • Function definition determines whether a parameter’s passing style is by value or by reference

  42. Reference Parameters • Reference parameter form ptypei &pnamei void swap(int &a, int &b)

  43. Reconsider int main() { int number1 = promptAndRead(); int number2 = promptAndRead(); if (number1 > number2) { Swap(number1, number2); } cout << "The numbers in sorted order: " << number1 << ", " << number2 << endl; return 0; }

  44. Passed by reference -- in aninvocation the actualparameter is given ratherthan a copy Return statement notnecessary for void functions Using Formal Parameters void swap(int &a, int &b) { int temp = a; a = b; b = temp; return; }

  45. int i = 5; int j = 6; swap(i, j); int a = 7; int b = 8; swap(b, a); void swap(int &a, int &b) { int temp = a; a = b; b = temp; return; } Consider

  46. Why is myNumber a reference parameter? Why is the stream a reference parameter? Extraction • Function to extract a value from a given stream void getNumber(int &myNumber, istream &sin) { sin >> myNumber; return; }

  47. Getnum.cpp int main() { ifstream fin("mydata.txt"); int number1; int number2; cout << "Enter number: "; GetNumber(number1, cin); // not needed: cout << "Enter number: "; GetNumber(number2, fin); if (number1 > number2) { swap(number1, number2); } cout << "The numbers in sorted order: " << number1 << ", " << number2 << endl; return 0; }

  48. Constant Parameters • The const modifier can be applied to formal parameter declarations • const indicates that the function may not modify the parameter void promptAndGet(int &n, const string &s) { cout << s ; cin >> n ; // s = "Got it"; // illegal assignment } // caught by compiler • Sample invocation int x; promptAndGet(x, "Enter number (n): ");

  49. Constant Parameters • Usefulness • When we want to pass an object by reference, but we do not want to let the called function modify the object • Why not just pass the object by value? • Wasteful to make copies of large objects

More Related