You are on page 1of 23

١٠/٠١/٤٠

Chapter 3: Expressions and Interactivity Topics

Starting Out with C++ 3.1 The cin Object


Early Objects
Eighth Edition 3.2 Mathematical Expressions
by Tony Gaddis, Judy Walters, 3.3 Data Type Conversion and Type Casting
and Godfrey Muganda

3.4 Overflow and Underflow

3.5 Named Constants

Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 3-2

١
١٠/٠١/٤٠

Topics (continued) 3.1 The cin Object

3.6 Multiple and Combined Assignment • Standard input object


• Like cout, requires iostream file
3.7 Formatting Output • Used to read input from keyboard
3.8 Working with Characters and Strings • Often used with cout to display a user
prompt first
3.9 Using C-Strings • Data is retrieved from cin with >>
3.10 More Mathematical Library Functions • Input data is stored in one or more
variables
Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 3-3 Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 3-4

٢
١٠/٠١/٤٠

The cin Object The cin Object

• User input goes from keyboard to the input • Can be used to input multiple values
buffer, where it is stored as characters cin >> height >> width;

• cin converts the data to the type that • Multiple values from keyboard must be
separated by spaces or [Enter]
matches the variable
• Must press [Enter] after typing last value
int height;
cout << "How tall is the room? "; • Multiple values need not all be of the same type
cin >> height; • Order is important; first value entered is stored
in first variable, etc.

Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 3-5 Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 3-6

٣
١٠/٠١/٤٠

3.2 Mathematical Expressions Using Mathematical Expressions

• An expression can be a constant, a • Can be used in assignment statements, with


variable, or a combination of constants
cout, and in other types of statements
and variables combined with operators
• Examples: This is an
• Can create complex expressions using expression
multiple mathematical operators area = 2 * PI * radius;
• Examples of mathematical expressions: cout << "border is: " << (2*(l+w));
2
height These are
expressions
a + b / c
Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 3-7 Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 3-8

٤
١٠/٠١/٤٠

Order of Operations Associativity of Operators

• In an expression with > 1 operator, • - (unary negation) associates right to left


evaluate in this order • * / % + - all associate left to right
Do first: ( ) expressions in parentheses • parentheses ( ) can be used to override the
Do next:- (unary negation) in order, left to right order of operations
2 + 2 * 2 – 2 = 4
Do next: * / % in order, left to right
(2 + 2) * 2 – 2 = 6
Do last: + - in order, left to right
2 + 2 * (2 – 2) = 2
• In the expression 2 + 2 * 2 – 2 , (2 + 2) * (2 – 2) = 0
Evaluate Evaluate Evaluate
2nd 1st 3rd
Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 3-9 Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 3-10

٥
١٠/٠١/٤٠

3.3 Data Type Conversion


Algebraic Expressions and Type Casting

• Multiplication requires an operator


Area = lw is written as Area = l * w; • Operations are performed between
• There is no exponentiation operator
operands of the same type
Area = s2 is written as Area = pow(s, 2); • If operands do not have the same type,
(note: pow requires the cmath header file) C++ will automatically convert one to be
• Parentheses may be needed to maintain order of the type of the other
operations
is written as • This can impact the results of calculations
m = (y2-y1)/(x2-x1);

Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 3-11 Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 3-12

٦
١٠/٠١/٤٠

Hierarchy of Data Types Type Coercion


• Coercion: automatic conversion of an
• Highest long double
double operand to another data type
float
unsigned long • Promotion: converts to a higher type
long
unsigned int • Demotion: converts to a lower type
• Lowest int

• Ranked by largest number they can hold

Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 3-13 Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 3-14

٧
١٠/٠١/٤٠

Coercion Rules Coercion Rules – Important Notes

1) char, short, unsigned short are 1) If demotion is required to use the =


automatically promoted to int operator,
- the stored result may be incorrect if there
2) When operating on values of different is not enough space available in the
data types, the lower-ranked one is receiving variable
promoted to the type of the higher one. - floating-point values are truncated when
assigned to integer variables
3) When using the = operator, the type of
expression on right will be converted to 2) Coercion affects the value used in a
the type of variable on left calculation. It does not change the
type associated with a variable.
Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 3-15 Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 3-16

٨
١٠/٠١/٤٠

Type Casting More Type Casting Examples

• Used for manual data type conversion char ch = 'C';


cout << ch << " is stored as "
• Format
<< static_cast<int>(ch);
static_cast<Data Type>(Value)
• Example: gallons = static_cast<int>(area/500);
cout << static_cast<int>(4.2);
// Displays 4 avg = static_cast<double>(sum)/count;

Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 3-17 Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 3-18

٩
١٠/٠١/٤٠

Older Type Cast Styles 3.4 Overflow and Underflow


double Volume = 21.58;
int intVol1, intVol2;
intVol1 = (int) Volume; // C-style • Occurs when assigning a value that is too
// cast large (overflow) or too small (underflow) to
intVol2 = int (Volume); //Prestandard be held in a variable
// C++ style
// cast • The variable contains a value that is
C-style cast uses prefix notation ‘wrapped around’ the set of possible values
Prestandard C++ cast uses functional notation
static_cast is the current standard

Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 3-19 Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 3-20

١٠
١٠/٠١/٤٠

Overflow Example Handling Overflow and Underflow

// Create a short int initialized to Different systems handle the problem


// the largest value it can hold differently. They may
short int num = 32767;
– display a warning / error message, or display a
cout << num; // Displays 32767 dialog box and ask what to do
num = num + 1; – stop the program
cout << num; // Displays -32768
– continue execution with the incorrect value

Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 3-21 Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 3-22

١١
١٠/٠١/٤٠

3.5 Named Constants Benefits of Named Constants


• Also called constant variables • Makes program code more readable by
• Variables whose content cannot be changed documenting the purpose of the constant in
during program execution the name:
const double TAX_RATE = 0.0675;
• Used for representing constant values with

descriptive names
salesTax = purchasePrice * TAX_RATE;
const double TAX_RATE = 0.0675;
const int NUM_STATES = 50; • Simplifies program maintenance:
const double TAX_RATE = 0.0725;
• Often named in uppercase letters
Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 3-23 Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 3-24

١٢
١٠/٠١/٤٠

const vs. #define


3.6 Multiple and Combined Assignment
#define no ;
goes here • The assignment operator (=) can be used
– C-style of naming constants
#define NUM_STATES 50 multiple times in an expression
– Interpreted by pre-processor rather than x = y = z = 5;
compiler
• Associates right to left
– Does not occupy a memory location like a
constant variable defined with const x = (y = (z = 5));
– Instead, causes a text substitution to occur. In Done Done Done
above example, every occurrence in program of 3rd 2nd 1st
NUM_STATES will be replaced by 50
Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 3-25 Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 3-26

١٣
١٠/٠١/٤٠

Combined Assignment More Examples

• Applies an arithmetic operation to a x += 5; means x = x + 5;


variable and assigns the result as the new x -= 5; means x = x – 5;
value of that variable x *= 5; means x = x * 5;
• Operators: += -= *= /= %= x /= 5; means x = x / 5;
• Also called compound operators or x %= 5; means x = x % 5;
arithmetic assignment operators The right hand side is evaluated before the
• Example: combined assignment operation is done.
sum += amt; is short for sum = sum + amt; x *= a + b; means x = x * (a + b);

Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 3-27 Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 3-28

١٤
١٠/٠١/٤٠

3.7 Formatting Output Stream Manipulators


• Can control how output displays for
numeric and string data
– size
• Used to control features of an output field
– position • Some affect just the next value displayed
– number of digits – setw(x): Print in a field at least x spaces
• Requires iomanip header file wide. It will use more spaces if specified field
width is not big enough.

Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 3-29 Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 3-30

١٥
١٠/٠١/٤٠

Stream Manipulators Manipulator Examples


• Some affect values until changed again
– fixed: Use decimal notation (not E-notation) for const float e = 2.718;
floating-point values. float price = 18.0; Displays
– setprecision(x): cout << setw(8) << e << endl; ^^^2.718
• When used with fixed, print floating-point value using x
digits after the decimal.
cout << left << setw(8) << e
• Without fixed, print floating-point value using x significant << endl; 2.718^^^
digits.
cout << setprecision(2);
– showpoint: Always print decimal for floating-point
values. cout << e << endl; 2.7
– left, right: left-, right justification of value cout << fixed << e << endl; 2.72
cout << setw(6) << price; ^18.00
Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 3-31 Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 3-32

١٦
١٠/٠١/٤٠

3.8 Working with Characters and Strings String Input

Reading in a string object


• char: holds a single character
string str;
• string: holds a sequence of characters
cin >> str; // Reads in a string
• Both can be used in assignment statements // with no blanks

• Both can be displayed with cout and << getline(cin, str); // Reads in a string
// that may contain
// blanks

Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 3-33 Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 3-34

١٧
١٠/٠١/٤٠

String Operators
Character Input
= Assigns a value to a string
Reading in a character: string words;
char ch; words = "Tasty ";
cin >> ch; // Reads in any non-blank char + Joins two strings together
cin.get(ch); // Reads in any char string s1 = "hot", s2 = "dog";
string food = s1 + s2; // food = "hotdog"
ch = cin.get;// Reads in any char
+= Concatenates a string onto the end of another one
cin.ignore();// Skips over next char in
words += food; // words now = "Tasty hotdog"
// the input buffer

Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 3-35 Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 3-36

١٨
١٠/٠١/٤٠

string Member Functions 3.9 Using C-Strings


• length() – the number of characters in a string • C-string is stored as an array of characters
• Programmer must indicate maximum number of
string firstPrez="George Washington"; characters at definition
int size=firstPrez.length(); // size is 17 const int SIZE = 5;
char temp[SIZE] = "Hot";
• assign() – put repeated characters in a string.
Can be used for formatting output. • NULL character (\0) is placed after final
character to mark the end of the string
string equals; H o t \0
equals.assign(80,'='); • Programmer must make sure array is big enough
… for desired use; temp can hold up to 4
cout << equals << endl; characters plus the \0.
cout << "Total: " << total << endl;
Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 3-37 Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 3-38

١٩
١٠/٠١/٤٠

C-String Input
C-String Initialization vs. Assignment
• Reading in a C-string
const int SIZE = 10; • A C-string can be initialized at the time of its
char Cstr[SIZE]; creation, just like a string object
cin >> Cstr; // Reads in a C-string with no const int SIZE = 10;
// blanks. Will write past the
// end of the array if input string char month[SIZE] = "April";
// is too long.
• However, a C-string cannot later be assigned a
cin.getline(Cstr, 10);
value using the = operator; you must use the
// Reads in a C-string that may strcpy() function
// contain blanks. Ensures that <= 9
// chars are read in. char month[SIZE];
• Can also use setw() and width() to control input field month = "August" // wrong!
widths strcpy(month, "August"); //correct

Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 3-39 Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 3-40

٢٠
١٠/٠١/٤٠

3.10 More Mathematical Library


C-String and Keyboard Input Functions
• Must use cin.getline()to put keyboard input • These require cmath header file
into a C-string • Take double arguments and return a
• Note that cin.getline() ≠ getline() double
• Must indicate the target C-string and maximum
number of characters to read:
• Commonly used functions
abs Absolute value
const int SIZE = 25; sin Sine
char name[SIZE]; cos Cosine
cout << "What's your name? "; tan Tangent
cin.getline(name, SIZE); sqrt Square root
log Natural (e) log
pow Raise to a power
Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 3-41 Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 3-42

٢١
١٠/٠١/٤٠

More Mathematical Library Functions More on Random Numbers

These require cstdlib header file • Use time() to generate different seed values
• rand each time that a program runs:
– Returns a random number between 0 and the #include <ctime> //needed for time()
largest int the computer holds …
– Will yield the same sequence of numbers each unsigned seed = time(0);
time the program is run srand(seed);
• srand(x) • Random numbers can be scaled to a range:
– Initializes random number generator with int max=6;
unsigned int x. x is the “seed value”. int num;
– Should be called at most once in a program
num = rand() % max + 1;
Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 3-43 Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 3-44

٢٢
١٠/٠١/٤٠

Chapter 3: Expressions and Interactivity

Starting Out with C++


Early Objects
Eighth Edition

by Tony Gaddis, Judy Walters,


and Godfrey Muganda

Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

٢٣

You might also like