0% found this document useful (0 votes)
117 views36 pages

Chapter 3: Expressions and Interactivity: Starting Out With C++ Early Objects Ninth Edition

Programming Design
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)
117 views36 pages

Chapter 3: Expressions and Interactivity: Starting Out With C++ Early Objects Ninth Edition

Programming Design
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/ 36

Chapter 3: Expressions and Interactivity

Starting Out with C++


Early Objects
Ninth Edition

by Tony Gaddis, Judy Walters,


and Godfrey Muganda

Copyright © 2017, 2014 Pearson Education, Inc.


Topics
3.1 The cin Object

3.2 Mathematical Expressions

3.3 Named Constants

3.4 Multiple and Combined Assignment

3.5 Formatting Output

3.6 Working with Characters and Strings

3.7 More Mathematical Library Functions

Copyright © 2017, 2014 Pearson Education, Inc. 3-2


3.1 The cin Object
• cin is the standard input object
• Like cout, requires iostream file
• Used to read input from keyboard
• Often used with cout to display a user
prompt first
• Data is retrieved from cin with >>, the
stream extraction operator
• Input data is stored in one or more
variables
Copyright © 2017, 2014 Pearson Education, Inc. 3-3
The cin Object

• User input goes from keyboard to the input


buffer, where it is stored as characters
• cin converts the data to the type that
matches the variable
int height;
cout << "How tall is the room? ";
cin >> height;

Copyright © 2017, 2014 Pearson Education, Inc. 3-4


The cin Object

• Can be used to input multiple values


cin >> height >> width;
• Multiple values from keyboard must be
separated by spaces or [Enter]
• Must press [Enter] after typing last value
• Multiple values need not all be of the same type
• Order is important; first value entered is stored
in first variable, etc.

Copyright © 2017, 2014 Pearson Education, Inc. 3-5


3.2 Mathematical Expressions
• An expression is something that can be
evaluated to produce a value.
• It can be a constant, a variable, or a combination
of constants and variables combined with
operators and grouping symbols
• We can create complex expressions using
multiple mathematical operators
• Examples of mathematical expressions:
2
height
a + b / c
Copyright © 2017, 2014 Pearson Education, Inc. 3-6
Using Mathematical Expressions

• Can be used in assignment statements, with


cout, and in other types of statements
• Examples: This is an
expression
area = 2 * PI * radius;
cout << "border is: " << (2*(l+w));

These are
expressions

Copyright © 2017, 2014 Pearson Education, Inc. 3-7


Order of Operations

In an expression with > 1 operator, evaluate


it in this order:
Do first: ( ) expressions in parentheses
- (unary negation) in order, left to right
Do next:
Do next: * / % in order, left to right

Do last: + - in order, left to right


Ex: In the expression 2 + 2 * 2 – 2 ,
Evaluate Evaluate Evaluate
2nd 1st 3rd
Copyright © 2017, 2014 Pearson Education, Inc. 3-8
Associativity of Operators

• - (unary negation) associates right to left


• * / % + - all associate left to right
• parentheses ( ) can be used to override the
order of operations
Expression Value
2 + 2 * 2 – 2 4
(2 + 2) * 2 – 2 6
2 + 2 * (2 – 2) 2
(2 + 2) * (2 – 2) 0
Copyright © 2017, 2014 Pearson Education, Inc. 3-9
Algebraic Expressions
• Multiplication requires an operator
Area = lw is written as Area = l * w;
• There is no exponentiation operator
Area = s2 is written as Area = pow(s, 2);
(note: pow requires the cmath header file)

• Parentheses may be needed to maintain order of


operations
y 2  y1 is written as
m
x 2  x1 m = (y2-y1)/(x2-x1);

Copyright © 2017, 2014 Pearson Education, Inc. 3-10


3.3 Data Type Conversion
and Type Casting

• Operations are performed between


operands of the same type
• If operands do not have the same type,
C++ will automatically convert one to be
the type of the other
• This can impact the results of calculations

Copyright © 2017, 2014 Pearson Education, Inc. 3-11


Hierarchy of Data Types

• Highest long double


double
float
unsigned long long int
long long int
unsigned long int
long int
unsigned int
• Lowest int
• Ranked by largest number they can hold
Copyright © 2017, 2014 Pearson Education, Inc. 3-12
3.5 Named Constants
• Also called constant variables
• Variables whose content cannot be changed
during program execution
• Used for representing constant values with
descriptive names
const double TAX_RATE = 0.0775;
const int NUM_STATES = 50;
• Often named in uppercase letters
Copyright © 2017, 2014 Pearson Education, Inc. 3-13
Defining and Initializing
Named Constants
• The value of a named constant must be
assigned when the variable is defined:
const int CLASS_SIZE = 24;
• An error occurs if you try to change the value
stored in a named constant after it is defined:
// This won’t work
CLASS_SIZE = CLASS_SIZE + 1;

Copyright © 2017, 2014 Pearson Education, Inc. 3-14


Benefits of Named Constants
• They make program code more readable by
documenting the purpose of the constant in
the name:
const double TAX_RATE = 0.0775;
. . .
salesTax = purchasePrice * TAX_RATE;
• They improve accuracy and simplify program
maintenance:
const double TAX_RATE = 0.0775;
Copyright © 2017, 2014 Pearson Education, Inc. 3-15
3.6 Multiple and Combined Assignment

• The assignment operator (=) can be used


multiple times in an expression
x = y = z = 5;
• Associates right to left
x = (y = (z = 5));
Done Done Done
3rd 2nd 1st

Copyright © 2017, 2014 Pearson Education, Inc. 3-16


Combined Assignment
• Applies an arithmetic operation to a
variable and assigns the result as the new
value of that variable
• Operators: += -= *= /= %=
• These are also called compound operators
or arithmetic assignment operators
• Example:
sum += amt; is short for sum = sum + amt;

Copyright © 2017, 2014 Pearson Education, Inc. 3-17


More Examples
x += 5; means x = x + 5;
x -= 5; means x = x – 5;
x *= 5; means x = x * 5;
x /= 5; means x = x / 5;
x %= 5; means x = x % 5;
The right hand side is evaluated before the
combined assignment operation is done.
x *= a + b; means x = x * (a + b);

Copyright © 2017, 2014 Pearson Education, Inc. 3-18


3.7 Formatting Output
• We can control how output displays for
numeric and string data
– size
– position
– number of digits
• This requires the iomanip header file

Copyright © 2017, 2014 Pearson Education, Inc. 3-19


Copyright © 2017, 2014 Pearson Education, Inc. 1-20
Stream Manipulators
• Are used to control features of an output field
• Some affect just the next value displayed
setw(x): Print a value in a field at least x
spaces wide.
– It will use more spaces if the specified field width is not
big enough.
– It right-justifies the value if it does not require x spaces.
– Decimal points in floating-point values use a space.
– All characters in strings, including space characters, use
space

Copyright © 2017, 2014 Pearson Education, Inc. 3-21


Stream Manipulators
• Some affect values until changed again
– fixed: Use decimal notation (not E-notation)
for floating-point values.
– setprecision(x):
• When used with fixed, print floating-point value
using x digits after the decimal.
• Without fixed, print floating-point value using x
significant digits.
• Rounding is used if x is smaller than the number of
significant digits

Copyright © 2017, 2014 Pearson Education, Inc. 3-22


Stream Manipulators
• Some additional manipulators:

– showpoint: Always print a decimal point for


floating-point values. This is useful with
fixed and setprecision when printing
monetary values.

– left, right: left- or right justification of a


value in a field.

Copyright © 2017, 2014 Pearson Education, Inc. 3-23


Manipulator Examples
const double e = 2.718;
double price = 18.0; Displays
cout << setw(8) << e << endl; ^^^2.718
cout << left << setw(8) << e
<< endl; 2.718^^^
cout << setprecision(2);
cout << e << endl; 2.7
cout << fixed << e << endl; 2.72
cout << setw(6) << price; 18.00^

Copyright © 2017, 2014 Pearson Education, Inc. 3-24


3.8 Working with Characters and Strings

• char: holds a single character


• string: holds a sequence of characters
• Both can be used in assignment statements
• Both can be displayed with cout and <<

Copyright © 2017, 2014 Pearson Education, Inc. 3-25


String Input

Reading in a string object


string str;
cin >> str; // Reads in a string
// with no blanks
getline(cin, str); // Reads in a string
// that may contain
// blanks

Copyright © 2017, 2014 Pearson Education, Inc. 3-26


Character Input

Reading in a character:
char ch;
cin >> ch; // Reads in any non-blank char
cin.get(ch); // Reads in any char
ch=cin.get();// Reads in any char
cin.ignore();// Skips over next char in
// the input buffer

Copyright © 2017, 2014 Pearson Education, Inc. 3-27


string Member Functions
• length() – the number of characters in a string

string firstPrez="George Washington";


int size=firstPrez.length(); // size is 17

• length() includes blank characters

• length() does not include the '\0' null


character that terminates the string

Copyright © 2017, 2014 Pearson Education, Inc. 3-28


String Operators
= Assigns a value to a string
string words;
words = "Tasty ";

+ Joins two strings together


string s1 = "hot", s2 = "dog";
string food = s1 + s2; // food = "hotdog"
+= Concatenates a string onto the end of another one
words += food; // words now = "Tasty hotdog"

Copyright © 2017, 2014 Pearson Education, Inc. 3-29


Using C-Strings
• A C-string is stored as an array of characters
• The programmer must indicate the maximum
number of characters at definition
const int SIZE =5;
char temp[SIZE] = "Hotter";
• NULL character (\0) is placed after final
character to mark the end of the string
H o t \0
• The programmer must make sure that the array
is big enough for desired use. temp can hold up
to 4 characters plus the \0.

Copyright © 2017, 2014 Pearson Education, Inc. 3-30


3.9 More Mathematical Library Functions
• These require cmath header file
• They take double arguments and return a
double
• Some commonly used functions
abs Absolute value
sin Sine
cos Cosine
tan Tangent
sqrt Square root
log Natural (e) log
pow Raise to a power
Copyright © 2017, 2014 Pearson Education, Inc. 3-31
Copyright © 2017, 2014 Pearson Education, Inc. 1-32
Copyright © 2017, 2014 Pearson Education, Inc. 1-33
Table : Expressions and Equations

Copyright © 2017, 2014 Pearson Education, Inc. 0-34


Evaluating a Mathematical Expression
EXPRESSION  5 * (X+Y) - 4 * Y/(Z+6)
X=2, Y=3, Z=6

Copyright © 2017, 2014 Pearson Education, Inc. 0-35


Evaluating a Relational Expression
A-2 > B, A=6, B=8

Copyright © 2017, 2014 Pearson Education, Inc. 0-36

You might also like