Presentation is loading. Please wait.

Presentation is loading. Please wait.

COMS 261 Computer Science I

Similar presentations


Presentation on theme: "COMS 261 Computer Science I"— Presentation transcript:

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

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

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 Utilize member functions In general
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 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 Definition float circleArea (float r) {
const float Pi = ; return Pi * r * r; } Formal parameter Return type Function name Local object definition Function body Return statement

17 Function Invocation cout << circleArea(MyRadius) << endl;
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().

18 Simple Programs Single file Functions use value parameter passing
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 // main(): manage circle computation
#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 = ; 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

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

24 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;

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

26 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

27 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; }

28 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;

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

30 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

31 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

32 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

33 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; // illegal insert

34 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

35 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

36 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 2 } cout << i << endl; return 0;

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

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

39 Using Formal Parameters
Code does NOT do what we want

40 Consider A parameter passing style where
Changes to the formal parameter change the actual parameter

41 That would work!

42 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

43 Reference Parameters Reference parameter form ptypei &pnamei
void swap(int &a, int &b)

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

45 Using Formal Parameters
void swap(int &a, int &b) { int temp = a; a = b; b = temp; return; } Passed by reference -- in an invocation the actual parameter is given rather than a copy Return statement not necessary for void functions

46 Consider 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; }

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

48 Getnum.cpp int main() { ifstream fin("mydata.txt"); int number1;
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;

49 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): ");

50 Constant Parameters Usefulness Why not just pass the object by value?
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


Download ppt "COMS 261 Computer Science I"

Similar presentations


Ads by Google