coms 261 computer science i

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

Upload: kirsi

Post on 05-Jan-2016

50 views

Category:

Documents


0 download

DESCRIPTION

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 - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: COMS 261 Computer Science I

1

COMS 261Computer Science I

Title: String Class

Date: October 7, 2005

Lecture Number: 16

Page 2: COMS 261 Computer Science I

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

Page 3: COMS 261 Computer Science I

3

Review

• Functions

• Libraries

• Prototypes

• Header files

• Strings

Page 4: COMS 261 Computer Science I

4

Outline

• Strings

• Function

Page 5: COMS 261 Computer Science I

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

Page 6: COMS 261 Computer Science I

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

Page 7: COMS 261 Computer Science I

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]

D a B o s s

index 0 1 2 3 4 5 6

myStr

Page 8: COMS 261 Computer Science I

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

Page 9: COMS 261 Computer Science I

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

Page 10: COMS 261 Computer Science I

10

C++ Strings

• Other member functions– The assignment operator (=)

– string grade = “A”;

– grade = “C”;

– append(string)

– string myStr = “Prof. P”;

– string myStr.append(“ Hemler”);

Page 11: COMS 261 Computer Science I

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)

Page 12: COMS 261 Computer Science I

12

Functions

• At this junction,

• I’d like to start talkin about the function

Page 13: COMS 261 Computer Science I

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

Page 14: COMS 261 Computer Science I

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)

Type of value that

the function returns

FunctionType FunctionName ( ParameterList )

A description of the form the

parameters (if any) are to take

Identifier name of

function

Page 15: COMS 261 Computer Science I

• 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

Function Definition

Page 16: COMS 261 Computer Science I

16

float circleArea (float r) {const float Pi = 3.1415;

return Pi * r * r;

}

Function Definition

Function body

Return statement

Local object definition

Return type Formal parameterFunction name

Page 17: COMS 261 Computer Science I

17

Function Invocation

cout << circleArea(MyRadius) << endl;

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().

Actual parameter

Page 18: COMS 261 Computer Science I

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

Page 19: COMS 261 Computer Science I

19

#include <iostream>using namespace std;float CircleArea(float r);

// main(): manage circle computationint 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 circlefloat CircleArea(float r) { const float Pi = 3.1415; return Pi * r * r;}

Page 20: COMS 261 Computer Science I

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

Page 21: COMS 261 Computer Science I

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

Page 22: COMS 261 Computer Science I

22

Returnvalue

FunctionInput stream

data

Output streamdata

Information to functioncan come from

parameters or an inputstream

Parameters

Information fromfunction can comethrough a return

value or an outputstream

Page 23: COMS 261 Computer Science I

PromptAndRead()

// promptAndRead(): prompt and extract next

// integer

int promptAndRead() {

cout << "Enter number (integer): ";

int Response;

cin >> Response;

return Response;

}

Page 24: COMS 261 Computer Science I

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;

}

Page 25: COMS 261 Computer Science I

Problem

• Definition– Input two numbers representing a range of

integers and compute and display the sum of the integers that lie in that range

Page 26: COMS 261 Computer Science I

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

Page 27: COMS 261 Computer Science I

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;

}

Page 28: COMS 261 Computer Science I

28

Range.cpp

// promptAndRead(): prompt & extract next integerint promptAndRead() {

cout << "Enter number (integer): ";int Response;cin >> Response;return Response;

}

// sum(): compute sum of integers in a ... bint sum(int a, int b) {

int total = 0;for (int i = a; i <= b; ++i) {

total += i;}return total;

}

Page 29: COMS 261 Computer Science I

Blocks and Local Scope

• A block is a list of statements within curly braces

{

.

.

.

}

Page 30: COMS 261 Computer Science I

Blocks and Local Scope

• Blocks can be put anywhere a statement can be put

• Blocks within blocks are nested blocks{

{

.

.

.

}

}

Block is nestedwithin another block

Page 31: COMS 261 Computer Science I

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}

Page 32: COMS 261 Computer Science I

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

Page 33: COMS 261 Computer Science I

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; // insert 1 } cout << i << endl; // illegal insert

}

Page 34: COMS 261 Computer Science I

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

Page 35: COMS 261 Computer Science I

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

Page 36: COMS 261 Computer Science I

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

Page 37: COMS 261 Computer Science I

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;

}

Page 38: COMS 261 Computer Science I

Using Formal Parameters

void swap(int a, int b) {

int temp = a;

a = b;

b = temp;

return;

}

Page 39: COMS 261 Computer Science I

Using Formal Parameters

Code does NOT do what we want

Page 40: COMS 261 Computer Science I

Consider

• A parameter passing style where– Changes to the formal parameter change

the actual parameter

Page 41: COMS 261 Computer Science I

41

That would work!

Page 42: COMS 261 Computer Science I

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

Page 43: COMS 261 Computer Science I

Reference Parameters

• Reference parameter form

ptypei &pnamei

void swap(int &a, int &b)

Page 44: COMS 261 Computer Science I

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;

}

Page 45: COMS 261 Computer Science I

Using Formal Parameters

void swap(int &a, int &b) {

int temp = a;

a = b;

b = temp;

return;

}

Return statement notnecessary for void functions

Passed by reference -- in aninvocation the actual

parameter is given ratherthan a copy

Page 46: COMS 261 Computer Science I

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;

}

Page 47: COMS 261 Computer Science I

Extraction

• Function to extract a value from a given streamvoid getNumber(int &myNumber, istream &sin) {

sin >> myNumber;

return;

}

Why is the stream a reference parameter?

Why is myNumber a reference parameter?

Page 48: COMS 261 Computer Science I

Getnum.cppint 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;

}

Page 49: COMS 261 Computer Science I

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 invocationint x;

promptAndGet(x, "Enter number (n): ");

Page 50: COMS 261 Computer Science I

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