Chapter 3
Chapter 3
(2 + 2) * 2 – 2 = 6
2 + 2 * (2 – 2) = 2
(2 + 2) * (2 – 2) = 0
Grouping with Parentheses
Evaluate Expressions
(a) (4 +17) % 2 – 1
= 21 % 2 – 1
= 1–1
= 0
(b) (6 – 3) * (2+7) / 3
=3*9/3
= 27 / 3
= 9
(c) (4 – 3) + ( 7 / 2)
=1+ 3
= 1+3
= 4
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);
• Parentheses may be needed to maintain order of operations:
y 2 − y1 is written as
m= m = (y2-y1) /(x2-x1);
x 2 − x1
Algebraic Expressions
When You Mix Apples with Oranges: Type Conversion
sum = sum + 1;
Continued…
The setw Stream Manipulator in Program 3-13
Stream Manipulators
• Some affect values until changed again:
• fixed : use decimal 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
• Showpoint : always print decimal for floating-point
values
cout<< fixed << showpoint << setprecision(2);
More Stream Manipulators in Program 3-17
Continued…
More Stream Manipulators in Program 3-17
Stream Manipulators
Working with Characters and string Objects
char ch;
cout << "Strike any key to continue";
cin >> ch;
Problem: will skip over blanks, tabs, <CR>
Use cin.get()
cin.get(ch);
sin Sine
cos Cosine
tan Tangent
sqrt Square root
log Natural (e) log
abs Absolute value (takes and returns an int)
More Mathematical Library Functions
• These require cstdlib header file
• rand(): returns a random number (int) between 0 and
the largest int the compute holds. Yields same sequence of
numbers each time program is run.
• srand(x): initializes random number generator with
unsigned int x
More Mathematical Library Functions
• Require cmath header file
• Take double as input, return a double
• Commonly used functions:
sin Sine
cos Cosine
tan Tangent
sqrt Square root
log Natural (e) log
abs Absolute value (takes and returns an int)
More Mathematical Library Functions
• These require cstdlib header file
• rand(): returns a random number (int) between 0 and
the largest int the computer holds. Yields same sequence of
numbers each time program is run.
• srand(x): initializes random number generator with
unsigned int x
Hand Tracing a Program
• Hand trace a program
- act as if you are the computer, executing a program:
• step through and ‘execute’ each statement, one-by-one
• record the contents of variables after statement
execution, using a hand trace chart (table)
• Useful to locate logic or mathematical errors
Program 3-27 with Hand Trace Chart