Operations Chapter 4 & Section 5.2

advertisement
Operations
Chapter 4
&
Section 5.2
1
Expressions
As we've seen, in a C++ program, any finite
sequence of objects and operations that combine
to produce a value is called an expression.
A temperature conversion example:
fahrenheit = 1.8 * celsius + 32;
We now consider C++ operations.
Why not
fahrenheit = 9/5 * celsius + 32; ?
2
Numeric Expressions
C++ provides four familiar arithmetic operators:
+ for performing addition
- for performing subtraction
* for performing multiplication
C++ provides
more than 50
operations
(See Appendix C)
/ for performing division
Each can be applied to either real (double) or
integer (int) [or character (char)] operands.
3
mult. symbols:
<<. ++, words ((sizeof)
Division
However, / behaves differently for int than for
double operands:
9.0 / 5.0 1.8
9.0 / 5  1.8
9 / 5.0  1.8
9/51
Type of Operands Kind of Division Performed
real
double
integer
int
Integer division calculates the quotient, but it also
calculates the remainder. To find it we can use the
modulus operator %; for example, 9 % 5 = 4.
4
“guzinta”
b = aq + r
Keep in mind
for Project 3
More examples:
4
56 / 10 = 5
1 / 2 =0
2 / 3 =0
456 % 100 = 56
56 % 10 = 6
1 % 2 =1
2 % 3 =2
456 / 100 =
What about mixed-mode (i.e., mixed-type) expressions?
Automatic Type Conversion (p. 73): Promotion:
"Narrower" types (fewer storage bits) "widened"
e.g., int  double; 9.0/5  9.0/5.0
Explicit Type Conversion (p. 73-4): Type Casting
Use type name to convert an expression:
double(intVal) or (double)intVal
Functional Notation
Cast Notation
5
b = aq + r
Assign 3 – chang maker
double(a) / double(b)
Numeric Functions
The library <cmath> contains a variety of
mathematical functions, including:
sin(x)
cos(x)
tan(x)
sqrt(x)
exp(x)
log(x)
log10(x)
asin(x)
acos(x)
atan(x)
abs(x)
pow(x, y)
floor(x)
ceil(x)
See Appendix D
for other math
functions and
other libraries.
Hyperbolic functions:
cosh(x), sinh(x), tanh(x)
6
sqrt(<0) nan -1.#IND
pow(x, 1/3)
efficiency –Asgn 2: quadratic
Using <cmath> functions
#include <iostream>
#include <cmath>
using namespace std;
int main()
C++ libraries whose names
start with 'c' are C libraries.
Their C-names do not have
the 'c' but have .h appended;
e.g., <math.h>
{
cout << "\nEnter base and exponent: ";
double base, exponent;
cin >> base >> exponent;
double result = pow(base, exponent);
cout << base << " raised to the power "
Essentially
same as
'\n'
<< exponent << " is " << result << endl;
}
7
Precedence
( or priority)
Issue: Is the value of the expression
2 + 3 * 4
(2 + 3) * 4  24
or
2 + (3 * 4)  14 ?
Operator precedence governs evaluation order.
* has higher precedence than +, so it is applied
first, making the answer 14.
8
See Slide
#32
int a = 8, b = 4, c = 2
pow(a, 2) + b * c -> 72
a/b+c -> 4 a/(b+c_ -> 1
Associativity
Does the expression
8-4-2
evaluate (8 - 4) - 2  2 or 8 - (4 - 2)  6 ?
Precedence doesn’t help us.
Associativity does. Since - is left-associative,
the left - is evaluated first.
Most of the C++ operators that we use associate left.
See Appendix C for a complete list.
See
App. D
9
int a = 8, b = 4, c = 2
a – b + c a / b*c
Assignment
Assignment is one operator that is rightassociative, which allows expressions like:
int w, x, y, z;
w = x = y = z = 0;
The rightmost = is applied first, assigning z zero,
Assignment operator
then y is assigned the value of z (0),
returns the value
being assigned.
then x is assigned the value of y (0),
and finally w is assigned the value of x (0).
w = ( x = ( y = ( z = 0)));
Mixed-mode assignments convert the
value to type of variable and assign it.
10
double pi = 3.1416;
int w = pi; 3 ; pi = w 3.0
y = 2*(x = a + b) + c
Assignment Shortcuts
Certain assignments are very common:
var = var + x;
// add x to var
var = var - y;
// sub y from var
C++ provides shortcuts for them:
var += x;
// add x to var
var -= y;
// sub y from var
Watch
out!
11
x += 2; x =+2;
Don’t use?
In General
Most arithmetic expressions of the form:
var = var D value;
can be written in the "shortcut" form:
var D= value;
Examples:
double x, y;
cin >> x >> y;
x *= 2.0;
// double x’s value
// decrease y by half
y /= 2.0;
12
Increment and Decrement
Other common assignments include:
var = var + 1;
// add 1 to var
var = var - 1;
// sub 1 from var
so C++ provides shortcuts for them, too:
var++;
// add 1 to var
++var;
var--;
// sub 1 from var
Integer
variables
only!
--var;
13
Prefix vs. Postfix
 As long as the increment (or decrement)
operator is used as a separate statement:
int y = 0, x = 0;
. . .
++x;
// x becomes 1
y++;
// y becomes 1
it makes no difference which
version is used.
14
However, ++ and -- can be used within
other expressions; then it does make a
difference whether it is prefix or postfix.

The prefix form of increment produces the
final (incremented) value as its result:
int x, y = 0;
x = 2 * (++y);

cout << x << " " << y; //
2 1 is displayed
The prefix decrement -- behaves similarly.
15
The postfix form of increment produces the
original (unincremented) value as its result:
int x, y = 0;
x = 2 * (y++);

cout << x << " " << y; // 0 1 is displayed
The prefix decrement -- behaves similarly.
16
I/O
In most programming languages, input and
output are performed by functions with
names like read() and print(). In C++,
however, (but not C) they are performed by
operators >> and <<:
input_stream >> variable
output_stream << expression.
17
printf, scanf
We know that:
cin >> variable reads a value from the
keyboard and assigns it to variable
cout << expression outputs the value of
expression to the screen.
But these are side effects. Because >> and <<
are operators, these i/o expessions must also
produce a value.
cin as its value;
cin >> variable returns ____
cout as its value.
cout << expression returns _____
18
Use at end of course
Why???
Arithmetic operators can be chained together in
expressions like a + b + c and a - b - c.
Input and output operators can also be chained; for
example:
cout << "Width =" << width << " ft.\n";
and
cin >> length >> width;
These work because of the values returned by
left
>> and << and both are ___-associative.
19
skim
Example:
cout << "Width =" << width << " ft.\n";
(cout << "Width =") << width << " ft.\n";
cout << width << " ft.\n";
____
(cout << width) << " ft.\n";
cout << " ft.\n";
____
cout;
____
Width = 8.5 ft.
20
skim
Relational Operations
§5.2
C++ provides six operators for comparisons.
Each has two operands and produces a bool
value (true or false):
x == y
x != y
x < y
x >= y
x > y
x <= y
Warning: 1 < x < 2
21
boolean expressions
Chap. 5: prep. for control
list on board
C, the parent language of C++, has no bool type.
Instead, it uses 0 to represent false
and nonzero values to represent true.
For upward compatibility, C++ also does this:
• 0 is interpreted as false
• nonzero is interpreted as true
For input and output, 0 is used for false, 1 for true
(see program on Slide #29)
unless boolalpha is inserted in an I/O statement
(see modification of program on Slide #29).
It remains in effect for rest of program (unless
noboolalpha is used in an I/O statement).
22
dec, oct, hex
One of the easiest mistakes to make
in C++ is using = (assignment)
in place of == (equality).
See the program on Slide #24.
Also, it can be dangerous to compare reals
with == and != when one or both of the
reals may have roundoff error.
See the program on Slide #25.
23
#include <iostream>
using namespace std;
int main()
{
int x;
cout << "Enter an integer: ";
cin >> x;
if (x = 99)
cout << "Yes\n";
else
cout << "No\n";
}
Executions:
Enter an integer: 99
Yes
Enter an integer: -99
Yes
Enter an integer: 0
Yes
With change:
if (x == 99)
Enter an integer: 99
Yes
Enter an integer: -99
No
Enter an integer: 0
No
24
Execution:
0 0
//-- Effect of roundoff error
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
for (float x = 0; x != 50.0; x = x + 0.1)
{
float y = x * sqrt(1 + sin(x));
cout << x << " " << y << endl;;
}
}
0.1
0.104873
0.2
0.218968
. . .
49.9998
42.937
50.0998 45.7826
50.1998 48.5246
. . .
100.099 76.3241
. . .
With change:
for (float x = 0; x < 50.0; x = x + 0.1)
Execution:
0 0
0.1
0.104873
0.2
0.218968
. . .
49.7998
49.8998
49.9998
36.9654
39.9954
42.937
or
abs(x - 50) >= 1E-10
25
Preconditions
Sometimes values must satisfy certain
requirements for a program to process them
(e.g., they must be positive).
e.g.,
Project 2.3
Such requirements are called preconditions or
assertions . They are boolean expressions that
must be true in order for the program to work
correctly.
A convenient way to check preconditions is to use
C++’s assert() mechanism.
if statement
later
26
Proj. 2 b^2 > 4ac
Proj. 3: payment > purchase
Assertions
#include <iostream>
#include <cassert>
using namespace std;
int main()
{
cout << "\nEnter the current month number: ";
int month;
cin >> month;
assert(month >= 1); assert(month <= 12);
// ...
}
assert() will halt the program if month < 1
or month > 12 and display a message.
27
assert1
Logical Operators
More complex boolean expressions can be built using
the logical operators:
b1 && b1
// true iff b1, b2 are both true
b1 || b2
// true iff b1 or b2 is true
!b
// true iff b is false
NOTE
Example:
cin >> month;
assert(1 <= month && month <= 12);
NOT:
assert(1 <= month <= 12);
28
assert1
#include <iostream>
using namespace std;
int main()
{
bool input1, input2, output;
cout << "Enter inputs: ";
cin >> input1 >> input2;
Executions:
Enter inputs: 0 1
Output for inputs 0 and 1 is 1
Enter inputs: 1 1
Output for inputs 1 and 1 is 0
output = (input1 || input2) && !(input1 && input2);
cout << "Output for inputs " << input1
<< " and " << input2 << " is " << output << '\n';
}
With change:
cout << "Output for inputs " << boolalpha << input1
<< " and " << input2 << " is " << output << '\n';
Enter inputs: 0 1
Output for inputs false and true is true
Binary HalfAdder: (§5.3)
Full Adder:
(Programming
Problems)
With change:
cin >> boolalpha >> input1 >> input2;
Enter inputs: false true
Output for inputs false and true is true
29
XOR circuit
See
App. D
Character Functions
The library <cctype> contains an assortment
of boolean character-processing functions:
isalpha(ch)
isdigit(ch)
islower(ch)
isspace(ch)
isprint(ch)
isalnum(ch)
iscntrl(ch)
isupper(ch)
ispunct(ch)
isgraph(ch)
and two case-conversion functions:
toupper(ch)
tolower(ch)
30
Examples:
Write an assertion that will halt the
program if a char object named ch is not an
uppercase letter:
assert('A' <= ch && ch <= 'Z');
or
assert(isupper(ch));
Write an assertion that will halt the
program if ch is not one of 'A' through 'G':
assert('A' <= ch && ch <= 'G');
31
use later - menu
Operator Precedence
( )
HIGHER
+ (positive), - (negative), ! (NOT)
*, /, %
+ (addition), - (subtraction)
<, <=, >, >=
<<, >>
54 operators
18 precedence
levels
==, !=
&&
When in doubt,
use parentheses!
||
=
See Appendix C for a complete list.
LOWER
32
Operator
::
::
.
[]
()
()
sizeof
++
-~
!
+
*
&
new
delete
()
.
->
*
/
%
+
<<
>>
<
<=
>
>=
==
!=
&
^
|
&&
||
? :
=
+=
-=
*=
/=
%=
&=
|=
^=
<<=
>>=
throw
,
Associativity
right
left
left
left
left
left
left
right
right
right
right
right
right
right
right
right
right
right
right
left
left
left
left
left
left
left
left
left
left
left
left
left
left
left
left
left
left
left
left
left
right
right
right
right
right
right
right
right
right
right
right
right
left
Overloadable
no
no
no
yes
yes
yes
yes
n/a
yes
yes
yes
yes
yes
yes
yes
yes
yes
yes
yes
no
yes
yes
yes
yes
yes
yes
yes
yes
yes
yes
yes
yes
yes
yes
yes
yes
yes
yes
yes
no
yes
yes
yes
yes
yes
yes
yes
yes
yes
yes
yes
yes
yes
Arity
unary
binary
binary
binary
binary
n/a
n/a
unary
unary
unary
unary
unary
unary
unary
unary
unary
unary
unary
binary
binary
binary
binary
binary
binary
binary
binary
binary
binary
binary
binary
binary
binary
binary
binary
binary
binary
binary
binary
binary
ternary
binary
binary
binary
binary
binary
binary
binary
binary
binary
binary
binary
unary
binary
Description
global scope
class scope
direct member selection
indirect member selection
subscript (array index)
function call
type construction
size (in bytes) of an object or type
increment
decrement
bitwise NOT
logical NOT
plus (sign)
minus (sign)
pointer dereferencing
get address of an object
memory allocation
memory deallocation
type conversion (cast)
direct member pointer selection
indirect member pointer selection
multiplication
division
modulus (remainder)
addition
subtraction
bit-shift left
bit-shift right
less-than
less-than-or-equal
greater-than
greater-than-or-equal
equality
inequality
bitwise AND
bitwise XOR
bitwise OR
logical AND
logical OR
conditional expression
assignment
addition-assignment shortcut
subtraction-assignment shortcut
multiplication-assignment shortcut
division-assignment shortcut
modulus-assignment shortcut
bitwise-AND-assignment shortcut
bitwise-OR-assignment shortcut
bitwise-XOR-assignment shortcut
bitshift-left-assignment shortcut
bitshift-right-assignment shortcut
throw an exception
expression separation
Download