week2ch4.ppt

© Copyright 2013 by Pearson Education, Inc. All Rights Reserved.

*

Chapter 4
Mathematical Functions, Characters, and Strings

© Copyright 2013 by Pearson Education, Inc. All Rights Reserved.

© Copyright 2013 by Pearson Education, Inc. All Rights Reserved.

*

Motivations

Suppose you need to estimate the area enclosed by four cities, given the GPS locations (latitude and longitude) of these cities, as shown in the following diagram. How would you write a program to solve this problem? You will be able to write such a program after completing this chapter.

Orlando (28.5383355,-81.3792365)

Savannah (32.0835407,-81.0998342)

Charlotte (35.2270869,-80.8431267)

Atlanta

(33.7489954,-84.3879824)

© Copyright 2013 by Pearson Education, Inc. All Rights Reserved.

*

Objectives

  • To solve mathematics problems by using the C++ mathematical functions (§4.2).
  • To represent characters using the char type (§4.3).
  • To encode characters using ASCII code (§4.3.1).
  • To read a character from the keyboard (§4.3.2).
  • To represent special characters using the escape sequences (§4.3.3).
  • To cast a numeric value to a character and cast a character to an integer (§4.3.4).
  • To compare and test characters (§4.3.5).
  • To program using characters (DisplayRandomCharacter, GuessBirthday) (§§4.4-4.5).
  • To test and convert characters using the C++ character functions (§4.6).
  • To convert a hexadecimal character to a decimal value (HexDigit2Dec) (§4.7).
  • To represent strings using the string type and introduce objects and instance functions (§4.8).
  • To use the subscript operator for accessing and modifying characters in a string (§4.8.1).
  • To use the + operator to concatenate strings (§4.8.2).
  • To compare strings using the relational operators (§4.8.3).
  • To read strings from the keyboard (§4.8.4).
  • To revise the lottery program using strings (LotteryUsingStrings) (§4.9).
  • To format output using stream manipulators (§4.10).
  • To read and write data from/to a file (§4.11).

© Copyright 2013 by Pearson Education, Inc. All Rights Reserved.

© Copyright 2013 by Pearson Education, Inc. All Rights Reserved.

*

Mathematical Functions

C++ provides many useful functions in the cmath header for performing common mathematical functions.

© Copyright 2013 by Pearson Education, Inc. All Rights Reserved.

*

Trigonometric Functions

Function Description

sin(radians) Returns the trigonometric sine of an angle in radians.

cos(radians) Returns the trigonometric cosine of an angle in radians.

tan(radians) Returns the trigonometric tangent of an angle in radians.

asin(a) Returns the angle in radians for the inverse of sine.

acos(a) Returns the angle in radians for the inverse of cosine.

atan(a) Returns the angle in radians for the inverse of tangent.

© Copyright 2013 by Pearson Education, Inc. All Rights Reserved.

*

Exponent Functions

image1.wmf

x

Function Description

exp(x) Returns e raised to power of x (ex).

log(x) Returns the natural logarithm of x (ln(x) = loge(x)).

log10(x) Returns the base 10 logarithm of x (log10(x)).

pow(a, b) Returns a raised to the power of b (ab).

sqrt(x) Returns the square root of x (�EMBED Equation.3���) for x >= 0.

_1173422839.unknown

© Copyright 2013 by Pearson Education, Inc. All Rights Reserved.

*

Rounding Functions

Function Description

ceil(x) x is rounded up to its nearest integer. This integer is returned

as a double value.

floor(x) x is rounded down to its nearest integer. This integer is returned

as a double value.

© Copyright 2013 by Pearson Education, Inc. All Rights Reserved.

*

The min, max, and abs Functions

  • max(2, 3) returns 3
  • max(2.5, 3.0) returns 4.0
  • min(2.5, 4.6) returns 2.5
  • abs(-2) returns 2
  • abs(-2.1) returns 2.1

© Copyright 2013 by Pearson Education, Inc. All Rights Reserved.

*

Case Study: Computing Angles of a Triangle

Write a program that prompts the user to enter the x- and y-coordinates of the three corner points in a triangle and then displays the triangle’s angles.

ComputeAngles

Run

A

B

C

a

b

c

A = acos((a * a - b * b - c * c) / (-2 * b * c))

B = acos((b * b - a * a - c * c) / (-2 * a * c))

C = acos((c * c - b * b - a * a) / (-2 * a * b))

x1, y1

x2, y2

x3, y3

© Copyright 2013 by Pearson Education, Inc. All Rights Reserved.

*

Character Data Type

char letter = 'A'; (ASCII)

char numChar = '4'; (ASCII)

NOTE: The increment and decrement operators can also be used on char variables to get the next or preceding character. For example, the following statements display character b.

char ch = 'a';

cout << ++ch;

© Copyright 2013 by Pearson Education, Inc. All Rights Reserved.

*

Read Characters

To read a character from the keyboard, use

cout << "Enter a character: ";

char ch;

cin >> ch;

© Copyright 2013 by Pearson Education, Inc. All Rights Reserved.

*

Escape Sequences for Special Characters

Character Escape Sequence Name ASCII Code

\b Backspace 8

\t Tab 9

\n Linefeed 10

\f Formfeed 12

\r Carriage Return 13

\\ Backslash 92

\' Single Quote 39

\" Double Quote 34

© Copyright 2013 by Pearson Education, Inc. All Rights Reserved.

Lab #1

  • Write a program that accepts as input a character variable called chrValue1.
  • If chrValue1 is ‘G’ or ‘g’ then write out to the screen “You entered a g”, if chrValue1 is ‘T’ or ‘t’ then write out to the screen “You entered a t”, if chrValue1 is ‘P’ or ‘p’ then write out to the screen “You entered a p”, otherwise output “You tricked me”.
  • Make sure you contain at least 3 comments
  • Variables are named correctly
  • Make sure that you use the switch statement and do not use any if statements.

*

© Copyright 2013 by Pearson Education, Inc. All Rights Reserved.

*

Appendix B: ASCII Character Set

ASCII Character Set is a subset of the Unicode from \u0000 to \u007f

© Copyright 2013 by Pearson Education, Inc. All Rights Reserved.

*

ASCII Character Set, cont.

ASCII Character Set is a subset of the Unicode from \u0000 to \u007f

© Copyright 2013 by Pearson Education, Inc. All Rights Reserved.

*

Casting between char and Numeric Types

int i = 'a';

// Same as int i = static_cast<int>('a');

char c = 97;

// Same as char c = static_cast<char>(97);

© Copyright 2013 by Pearson Education, Inc. All Rights Reserved.

*

Numeric Operators on Characters

The char type is treated as if it is an integer of the byte size. All numeric operators can be applied to char operands. A char operand is automatically cast into a number if the other operand is a number or a character. For example, the following statements

int i = '2' + '3'; // (int)'2' is 50 and (int)'3' is 51

cout << "i is " << i << endl; // i is decimal 101

int j = 2 + 'a'; // (int)'a' is 97

cout << "j is " << j << endl;

cout << j << " is the ASCII code for character " <<

static_cast<char>(j) << endl;

Display

i is 101

j is 99

99 is the ASCII code for character c

© Copyright 2013 by Pearson Education, Inc. All Rights Reserved.

*

Note

It is worthwhile to note that the ASCII for lowercase letters are consecutive integers starting from the code for 'a', then for 'b', 'c', ..., and 'z'. The same is true for the uppercase letters. Furthermore, the ASCII code for 'a' is greater than the code for 'A'. So 'a' - 'A' is the same as 'b' - 'B'. For a lowercase letter ch, its corresponding uppercase letter is static_cast<char>('A' + (ch - 'a')).

© Copyright 2013 by Pearson Education, Inc. All Rights Reserved.

*

Problem: Converting a Lowercase to Uppercase

ToUppercase

Run

Write a program that prompts the user to enter a lowercase letter and finds its corresponding uppercase letter.

© Copyright 2013 by Pearson Education, Inc. All Rights Reserved.

*

Comparing and Testing Characters

Two characters can be compared using the comparison operators just like comparing two numbers. This is done by comparing the ASCII codes of the two characters.

'a' < 'b' is true because the ASCII code for 'a' (97) is less than the ASCII code for 'b' (98).

'a' < 'A' is true because the ASCII code for 'a' (97) is less than the ASCII code for 'A' (65).

'1' < '8' is true because the ASCII code for '1' (49) is less than the ASCII code for '8' (56).

© Copyright 2013 by Pearson Education, Inc. All Rights Reserved.

*

Case Study: Generating Random Characters

Computer programs process numerical data and characters. You have seen many examples that involve numerical data. It is also important to understand characters and how to process them.

Every character has a unique ASCII code between 0 and 127. To generate a random character is to generate a random integer between 0 and 127. You learned how to generate a random number in §3.8. Recall that you can use the srand(seed) function to set a seed and use rand() to return a random integer. You can use it to write a simple expression to generate random numbers in any range. For example,

© Copyright 2013 by Pearson Education, Inc. All Rights Reserved.

*

Case Study: Generating Random Characters, cont.

DisplayRandomCharacter

rand() % 10

Returns a random integer between 0 and 9.

Returns a random integer between 50 and 99.

50 + rand() % 50

Returns a random number between a and a + b, excluding a + b.

a + rand() % b

© Copyright 2013 by Pearson Education, Inc. All Rights Reserved.

*

Case Study: Guessing Birthdays

This section uses the if statements to write an interesting game program. The program can find your birth date. The program prompts you to answer whether your birth date is in the following five sets of numbers:

GuessBirthday

Run

16 17 18 19

20 21 22 23

24 25 26 27

28 29 30 31

Set2

Set1

8 9 10 11

12 13 14 15

24 25 26 27

28 29 30 31

Set3

1 3 5 7

9 11 13 15

17 19 21 23

25 27 29 31

Set4

2 3 6 7

10 11 14 15

18 19 22 23

26 27 30 31

Set5

4 5 6 7

12 13 14 15

20 21 22 23

28 29 30 31

+

= 19

© Copyright 2013 by Pearson Education, Inc. All Rights Reserved.

*

Character Functions

CharacterFunctions

Run

Function Description

isdigit(ch) Returns true if the specified character is a digit.

isalpha(ch) Returns true if the specified character is a letter.

isalnum(ch) Returns true if the specified character is a letter or digit.

islower(ch) Returns true if the specified character is a lowercase letter.

isupper(ch) Returns true if the specified character is an uppercase letter.

isspace(ch) Returns true if the specified character is a whitespace character.

tolower(ch) Returns the lowercase of the specified character.

toupper(ch) Returns the uppercase of the specified character.

© Copyright 2013 by Pearson Education, Inc. All Rights Reserved.

*

Case Study: Converting a Hexadecimal Digit to a Decimal Value

Write a program that converts a hexadecimal digit into a decimal value.

HexDigit2Dec

Run

© Copyright 2013 by Pearson Education, Inc. All Rights Reserved.

*

The string Type

string s;

string message = "Programming is fun";

Function Description

Returns the number of characters in this string.

Same as length();

Returns the character at the specified index from this string.

length()

size()

at(index)

© Copyright 2013 by Pearson Education, Inc. All Rights Reserved.

*

String Subscript Operator

For convenience, C++ provides the subscript operator for accessing the character at a specified index in a string using the syntax stringName[index]. You can use this syntax to retrieve and modify the character in a string.

13

e

Indices

m

e

o

c

l

W

12

+

+

C

o

t

11

10

9

8

7

6

5

4

3

2

1

0

message

message.at(0)

message.at(13)

message.length is 14

© Copyright 2013 by Pearson Education, Inc. All Rights Reserved.

*

String Subscript Operator

string s = "ABCD";

s[0] = 'P';

cout << s[0] << endl;

© Copyright 2013 by Pearson Education, Inc. All Rights Reserved.

Lab #2

  • Enter a sample string that is at least 10 characters in length, no spaces.
  • Output to the screen the characters at the 1st, 3rd, 5th, 7th and 9th position in the string.
  • Make sure you contain at least 3 comments
  • Variables are named correctly

*

© Copyright 2013 by Pearson Education, Inc. All Rights Reserved.

*

Concatenating Strings

string s3 = s1 + s2;

message += " and programming is fun";

© Copyright 2013 by Pearson Education, Inc. All Rights Reserved.

*

Comparing Strings

You can use the relational operators ==, !=, <, <=, >, >= to compare two strings. This is done by comparing their corresponding characters on by one from left to right. For example,

string s1 = "ABC";

string s2 = "ABE";

cout << (s1 == s2) << endl; // Displays 0 (means false)

cout << (s1 != s2) << endl; // Displays 1 (means true)

cout << (s1 > s2) << endl; // Displays 0 (means false)

cout << (s1 >= s2) << endl; // Displays 0 (means false)

cout << (s1 < s2) << endl; // Displays 1 (means true)

cout << (s1 <= s2) << endl; // Displays 1 (means true)

© Copyright 2013 by Pearson Education, Inc. All Rights Reserved.

*

Reading Strings

1 string city;

2 cout << "Enter a city: ";

3 cin >> city; // Read to array city

4 cout << "You entered " << city << endl;

1 string city;

2 cout << "Enter a city: ";

3 getline(cin, city, '\n'); // Same as getline(cin, city)

4 cout << "You entered " << city << endl;

© Copyright 2013 by Pearson Education, Inc. All Rights Reserved.

*

Example

Write a program that prompts the user to enter two cities and displays them in alphabetical order.

OrderTwoCities

Run

© Copyright 2013 by Pearson Education, Inc. All Rights Reserved.

*

Case Study: Revising the Lottery Program Using Strings

A problem can be solved using many different approaches. This section rewrites the lottery program in Listing 3.7 using strings. Using strings simplifies this program.

LotteryUsingStrings

Run

© Copyright 2013 by Pearson Education, Inc. All Rights Reserved.

*

Formatting Console Output

Manipulator Description

setprecision(n) sets the precision of a floating-point number

fixed displays floating-point numbers in fixed-point notation

showpoint causes a floating-point number to be displayed with

a decimal point and trailing zeros even if it has

no fractional part

setw(width) specifies the width of a print field

left justifies the output to the left

right justifies the output to the right

© Copyright 2013 by Pearson Education, Inc. All Rights Reserved.

*

setprecision(n) Manipulator

double number = 12.34567;

cout << setprecision(3) << number << " "

<< setprecision(4) << number << " "

<< setprecision(5) << number << " "

<< setprecision(6) << number << endl;

displays

12.3□12.35□12.346□12.3457

© Copyright 2013 by Pearson Education, Inc. All Rights Reserved.

*

fixed Manipulator

double monthlyPayment = 345.4567;

double totalPayment = 78676.887234;

cout << fixed << setprecision(2)

<< monthlyPayment << endl

<< totalPayment << endl;

displays

345.46

78676.89

© Copyright 2013 by Pearson Education, Inc. All Rights Reserved.

*

showpoint Manipulator

cout << setprecision(6);

cout << 1.23 << endl;

cout << showpoint << 1.23 << endl;

cout << showpoint << 123.0 << endl;

displays

1.23

1.23000

123.000

© Copyright 2013 by Pearson Education, Inc. All Rights Reserved.

*

setw(width) Manipulator

cout << setw(8) << "C++" << setw(6) << 101 << endl;

cout << setw(8) << "Java" << setw(6) << 101 << endl;

cout << setw(8) << "HTML" << setw(6) << 101 << endl;

displays

□□□□□C++□□□101

□□□□Java□□□101

□□□□HTML□□□101

8

6

© Copyright 2013 by Pearson Education, Inc. All Rights Reserved.

*

left and right Manipulators

cout << right;

cout << setw(8) << 1.23 << endl;

cout << setw(8) << 351.34 << endl;

displays

□□□□1.23

□□351.34

© Copyright 2013 by Pearson Education, Inc. All Rights Reserved.

*

left and right Manipulators

cout << left;

cout << setw(8) << 1.23;

cout << setw(8) << 351.34 << endl;

displays

1.23□□□□351.34□□

© Copyright 2013 by Pearson Education, Inc. All Rights Reserved.

*

Example: Display a Table

Degrees Radians Sine Cosine Tangent

30 0.5236 0.5000 0.8660 0.5773

60 1.0472 0.8660 0.5000 1.7320

FormatDemo

Run

© Copyright 2013 by Pearson Education, Inc. All Rights Reserved.

*

Simple File Output

To write data to a file, first declare a variable of the ofstream type:

ofstream output;

To specify a file, invoke the open function from output object as follows:

output.open("numbers.txt");

Optionally, you can create a file output object and open the file in one statement like this:

ofstream output("numbers.txt");

To write data, use the stream insertion operator (<<) in the same way that you send data to the cout object. For example,

output << 95 << " " << 56 << " " << 34 << endl;

SimpleFileOutput

Run

© Copyright 2013 by Pearson Education, Inc. All Rights Reserved.

*

Simple File Input

To read data from a file, first declare a variable of the ifstream type:

ifstream input;

To specify a file, invoke the open function from input as follows:

input.open("numbers.txt");

Optionally, you can create a file output object and open the file in one statement like this:

ifstream input("numbers.txt");

To read data, use the stream extraction operator (>>) in the same way that you read data from the cin object. For example,

input << score1 << score2 << score3;

SimpleFileInput

Run

© Copyright 2013 by Pearson Education, Inc. All Rights Reserved.

Lab #3

  • Write a program that accepts as input a string variable called strFirstName, then another string variable called strLastName, and then string variable called strEmail.
  • Write out to a file each, however make sure it looks like :
  • First Name: David
  • Last Name: Wiesner
  • Email Addr: [email protected]
  • Make sure you contain at least 3 comments
  • Variables are named correctly
  • Program functions as expected

*

Orlando (28.5383355,-81.3792365)

Savannah (32.0835407,-81.0998342)

Charlotte (35.2270869,-80.8431267)

Atlanta

(33.7489954,-84.3879824)

Function Description

sin(radians) Returns the trigonometric sine of an angle in radians.

cos(radians) Returns the trigonometric cosine of an angle in radians .

tan(radians) Returns the trigonometric tangent of an angle in radians .

asin(a) Returns the angle in radians for the inverse of sine .

acos(a) Returns the angle in radians for the inverse of cosine.

atan(a) Returns the angle in radians for the inverse of tangent .

Function Description

exp(x) Returns e raised to power of x (e

x

).

log(x) Returns the natural logarithm of x (ln(x) = log

e

(x)).

log10(x) Returns the base 10 logarithm of x (log

10

(x)).

pow(a, b) Returns a raised to the power of b (a

b

).

sqrt(x) Returns the square root of x (

x

) for x >= 0.

Function Description

ceil(x) x is rounded up to its nearest integer. This integer is returned

as a double value.

floor(x) x is rounded down to its nearest integer. This integer is returned

as a double value.

A

B

C

a

b

c

A = acos((a * a - b * b - c * c) / (-2 * b * c))

B = acos((b * b - a * a - c * c) / (-2 * a * c))

C = acos((c * c - b * b - a * a) / (-2 * a * b))

x1, y1

x2, y2

x3, y3

Character Escape Sequence Name ASCII Code

\b Backspace 8

\t Tab 9

\n Linefeed 10

\f Formfeed 12

\r Carriage Return 13

\\ Backslash 92

\' Single Quote 39

\" Double Quote 34

rand()

%

10

Returns a random integer

between 0 and 9.

50

+ rand()

%

50

Returns a random integer

between 50 and 99.

a + rand()

%

b

Returns a random number between

a and a + b, excluding a + b.

Run

16 17 18

19

20 21 22 23

24 25 26 27

28 29 30 31

Set1

8 9 10 11

12 13 14 15

24 25 26 27

28 29 30 31

Set2

1 3 5 7

9 11 13 15

17

19

21 23

25 27 29 31

Set3

2 3 6 7

10 11 14 15

18

19

22 23

26 27 30 31

Set4

4 5

6 7

12 13 14 15

20 21 22 23

28 29 30 31

Set5

+

= 19

Function Description

isdigit(ch) Returns true if the specified character is a digit.

isalpha(ch) Returns true if the specified character is a letter.

isalnum(ch) Returns true if the specified character is a letter or digit.

islower(ch) Returns true if the specified character is a lowercase letter.

isupper(ch) Returns true if the specified character is an uppercase letter.

isspace(ch) Returns true if the specified character is a whitespace character.

tolower(ch) Returns the lowercase of the specified character .

toupper(ch) Returns the uppercase of the specified character .

Function Description

Returns the number of characters in this string.

Same as length();

Returns the character at the specified index from this string .

length()

size()

at(index)

Indices

W

e

l

c

o

m

e

t

o

C

+

+

0

1

2

3

4

5

6

7

8

9

10

11

12

13

message

message.at(0)

message.at(13)

message.length is 14

Manipulator

Description

setprecision(n) sets the precision of a floating

-

point number

fixed

displays

floating

-

point numbers in fixed

-

point notation

showpoint causes a floating

-

point number to

be displayed with

a decimal point

and

trailing zeros even if it has

no fractional part

setw(width) specifies the width of a print field

left justifies the output to the left

right

justifies the output to the right

□□□□□C++□□□101

□□□□Java□□□101

□□□□HTML□□□101

8

6