0% found this document useful (0 votes)
16 views

04 Math Functinos Chars and Strings

This document outlines topics related to mathematical functions, character data types, and strings in C++. It discusses built-in mathematical functions, character operations and ASCII values, generating random characters, and converting between data types. Example programs are provided to demonstrate computing triangle angles, uppercase conversion, and hexadecimal to decimal conversion using character functions. The document introduces strings as a data type and provides an outline for the chapter.

Uploaded by

maleksobhy17
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views

04 Math Functinos Chars and Strings

This document outlines topics related to mathematical functions, character data types, and strings in C++. It discusses built-in mathematical functions, character operations and ASCII values, generating random characters, and converting between data types. Example programs are provided to demonstrate computing triangle angles, uppercase conversion, and hexadecimal to decimal conversion using character functions. The document introduces strings as a data type and provides an outline for the chapter.

Uploaded by

maleksobhy17
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 41

Chapter 4: Mathematical

Functions, Characters, and Strings

Textbooks: Y. Daniel Liang, Introduction to Programming with C++, 3rd Edition


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

1
Outline
• Introduction
• Mathematical Functions
• Character Data Type and Operations
• Case Study: Generating Random Characters
• Case Study: Guessing Birthdays
• Character Functions
• Case Study: Converting Hexadecimal Decimal
• The string Type
• Case Study: Revising the Lottery Program Using Strings
• Formatting Console Output
• Simple File Input and Output

2
Outline
• Introduction
• Mathematical Functions
• Character Data Type and Operations
• Case Study: Generating Random Characters
• Case Study: Guessing Birthdays
• Character Functions
• Case Study: Converting Hexadecimal Decimal
• The string Type
• Case Study: Revising the Lottery Program Using Strings
• Formatting Console Output
• Simple File Input and Output

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

1. Trigonometric functions
2. Exponent functions
3. Service functions

To use them, you need to include:


#include <cmath>

5
Trigonometric Functions

6
Exponent Functions

7
Service Functions
Function Description Example
ceil(x) x is rounded up to its nearest ceil(2.1) returns 3.0
integer. This integer is ceil(-2.1) returns -2.0
returned as a double value.
floor(x) x is rounded down to its floor(2.1) returns 2.0
nearest integer. This integer floor(-2.1) returns -3.0
is returned as a double value.
min(x, y) Returns the minimum of x max(2, 3) returns 3
and y.
max(x, y) Returns the maximum of x min(2.5, 4.6) returns
and y. 2.5
abs(x) Returns the absolute value of abs(-2.1) returns 2.1
x.
8
Case Study: Computing Angles
of a Triangle

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

9
ComputeAngles.cpp 1/2
#include <iostream>
#include <cmath>
using namespace std;

int main()
{
// Prompt the user to enter three points
cout << "Enter three points: ";
double x1, y1, x2, y2, x3, y3;
cin >> x1 >> y1 >> x2 >> y2 >> x3 >> y3;

// Compute three sides


double a = sqrt((x2 - x3) * (x2 - x3) + (y2 - y3) * (y2 - y3));
double b = sqrt((x1 - x3) * (x1 - x3) + (y1 - y3) * (y1 - y3));
double c = sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2));
10
ComputeAngles.cpp 2/2
// Obtain three angles in radians
double A = acos((a * a - b * b - c * c) / (-2 * b * c));
double B = acos((b * b - a * a - c * c) / (-2 * a * c));
double C = acos((c * c - b * b - a * a) / (-2 * a * b));

// Display the angles in degress


const double PI = 3.14159;
cout << "The three angles are " << A * 180 / PI << " "
<< B * 180 / PI << " " << C * 180 / PI << endl;

return 0;
}

11
Outline
• Introduction
• Mathematical Functions
• Character Data Type and Operations
• Case Study: Generating Random Characters
• Case Study: Guessing Birthdays
• Character Functions
• Case Study: Converting Hexadecimal Decimal
• The string Type
• Case Study: Revising the Lottery Program Using Strings
• Formatting Console Output
• Simple File Input and Output

12
Character Data Type
• A character data type represents a single character.
char letter = 'A'; (ASCII)
char numChar = '4'; (ASCII)
• 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;
• The characters are encoded into numbers using the
ASCII code.
13
ASCII Character Set is a subset of the Unicode from \u0000 to \u007f
14
Read Characters
To read a character from the keyboard, use

cout << "Enter a character: ";


char ch;
cin >> ch; // Read a character

15
Escape Sequences
C++ uses a special notation to represent special character.

cout << "He said \"Hi\".\n";


The output is: He said "Hi".
16
Casting between char and
Numeric Types
• A char can be cast into any numeric type, and vice
versa.

int i = 'a';
cout << i; // print 97

char c = 97;
cout << c; // print 'a'

17
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.

Display

18
Example: Converting a Lowercase to
Uppercase
A program that prompts the user to enter a lowercase
letter and finds its corresponding uppercase letter.

19
Comparing and Testing Characters
• 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.
• The lower case of a letter is larger than its upper case by 32.
• Two characters can be compared using the comparison
operators just like comparing two numbers.
• 'a' < 'b' is true because the ASCII code for 'a' (97) is
less than the ASCII code for 'b' (98).
• 'a' < 'A' is false.
• '1' < '8' is true.

20
Outline
• Introduction
• Mathematical Functions
• Character Data Type and Operations
• Case Study: Generating Random Characters
• Case Study: Guessing Birthdays
• Character Functions
• Case Study: Converting Hexadecimal Decimal
• The string Type
• Case Study: Revising the Lottery Program Using Strings
• Formatting Console Output
• Simple File Input and Output

21
Case Study: Generating Random
Characters
The rand() function returns a random integer. You can
use it to write a simple expression to generate random
numbers in any range.

[a , a+b-1]
22
Case Study: Generating Random
Characters, cont.
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. The srand(seed) function is used to set a
seed.

// [startChar , endChar]

DisplayRandomCharacter Run
23
Outline
• Introduction
• Mathematical Functions
• Character Data Type and Operations
• Case Study: Generating Random Characters
• Case Study: Guessing Birthdays
• Character Functions
• Case Study: Converting Hexadecimal Decimal
• The string Type
• Case Study: Revising the Lottery Program Using Strings
• Formatting Console Output
• Simple File Input and Output

27
Character Functions
C++ contains functions for working with characters.

CharacterFunctions Run

and returns the ASCII integer value of


the Uppercase character 28
Example using Character
Functions

CharacterFunctions Run

29
Character Functions

• You can use isupper(), islower() and


isdigit() in the code below.

30
Outline
• Introduction
• Mathematical Functions
• Character Data Type and Operations
• Case Study: Generating Random Characters
• Case Study: Guessing Birthdays
• Character Functions
• Case Study: Converting Hexadecimal Decimal
• The string Type
• Case Study: Revising the Lottery Program Using Strings
• Formatting Console Output
• Simple File Input and Output

31
Case Study: Converting a Hexadecimal
Digit to a Decimal Value
A program that converts a hexadecimal digit to decimal.

HexDigit2Dec Run

32
HexDigit2Dec.cpp

33
Outline
• Introduction
• Mathematical Functions
• Character Data Type and Operations
• Case Study: Generating Random Characters
• Case Study: Guessing Birthdays
• Character Functions
• Case Study: Converting Hexadecimal Decimal
• The string Type
• Case Study: Revising the Lottery Program Using Strings
• Formatting Console Output
• Simple File Input and Output

34
The string Type
A string is a sequence of characters.
#include <string>
string s;
string message = "Programming is fun";

35
String Subscript Operator
C++ provides the subscript operator for accessing the
character at a specified index in a string using the
syntax stringName[index].
string message = "welcome to C++";
message.at(0) = 'W';
cout<< message.length()<< message[0]<< endl;
14W

36
Concatenating Strings
C++ provides the + operator for concatenating two strings.

string s3 = s1 + s2;

string m = "Good";
m += " morning";
m += '!';
cout << m << endl;
Good morning!
37
Comparing Strings
You can use the relational operators ==, !=, <, <=, >, >= to
compare two strings. This is done by comparing their
corresponding characters one by one from left to right.
For example,

38
Reading Strings
Reading the first word of the string:

Reading a line using getline(cin, s ):

39
Example: Order Two Cities
A program that prompts the user to enter two
cities and displays them in alphabetical order.

OrderTwoCities Run

40
OrderTwoCities.cpp
#include <iostream>
#include <string>
using namespace std;

int main() {
string city1, city2;
cout << "Enter the first city: ";
getline(cin, city1);
cout << "Enter the second city: ";
getline(cin, city2);

cout << "The cities in alphabetical order are ";


if (city1 < city2)
cout << city1 << " " << city2 << endl;
else
cout << city2 << " " << city1 << endl;

return 0;
} 41
Outline
• Introduction
• Mathematical Functions
• Character Data Type and Operations
• Case Study: Generating Random Characters
• Case Study: Guessing Birthdays
• Character Functions
• Case Study: Converting Hexadecimal Decimal
• The string Type
• Case Study: Revising the Lottery Program Using Strings
• Formatting Console Output
• Simple File Input and Output

52
Simple File Output
To write data to a file, You can create a file output
object and open the file in one statement like
this:
#include <fstream>
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;

Finally:
output.close();
SimpleFileOutput Run

53
Simple File Input
To read data from a file, first declare a variable of the ifstream
type:
#include <fstream>
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;
Finally:
SimpleFileInput Run
input.close();

54
Outline
• Introduction
• Mathematical Functions
• Character Data Type and Operations
• Case Study: Generating Random Characters
• Case Study: Guessing Birthdays
• Character Functions
• Case Study: Converting Hexadecimal Decimal
• The string Type
• Case Study: Revising the Lottery Program Using Strings
• Formatting Console Output
• Simple File Input and Output

55

You might also like