33
1 Operations Operations Chapter 4 4 & & Section 5.2 Section 5.2

1 Operations 4 & Section 5.2 Chapter 4 & Section 5.2

Embed Size (px)

Citation preview

Page 1: 1 Operations 4 & Section 5.2 Chapter 4 & Section 5.2

1

OperationsOperations

Chapter 4 4&&

Section 5.2Section 5.2

Page 2: 1 Operations 4 & Section 5.2 Chapter 4 & Section 5.2

ExpressionsExpressions

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.

2

Why notfahrenheit = 9/5 * celsius + 32; ?

Page 3: 1 Operations 4 & Section 5.2 Chapter 4 & Section 5.2

Numeric ExpressionsNumeric Expressions

C++ provides four familiar arithmetic operators:

+ for performing addition

- for performing subtraction

* for performing multiplication

/ for performing division

Each can be applied to either real (double) or integer (int) [or character (char)] operands. 3

C++ provides more than 50operations (See Appendix C)

mult. symbols:<<. ++, words ((sizeof)

Page 4: 1 Operations 4 & Section 5.2 Chapter 4 & Section 5.2

DivisionDivisionHowever, / behaves differently for int than for double operands:

1

1.81.8

1.8

4

9.0 / 5

9 / 5.0 Type of Operands Kind of Division Performed

int integerreal

9.0 / 5.0

9 / 5

double

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

“guzinta”b = aq + r

Page 5: 1 Operations 4 & Section 5.2 Chapter 4 & Section 5.2

More examples:

5

1

4

56

0 0

2

5

6

Keep in mind for Project 3

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 CastingUse type name to convert an expression:

double(intVal) or (double)intValFunctional Notation Cast Notation

b = aq + rAssign 3 – chang makerdouble(a) / double(b)

Page 6: 1 Operations 4 & Section 5.2 Chapter 4 & Section 5.2

Numeric FunctionsNumeric Functions

The library <cmath> contains a variety of mathematical functions, including:

sin(x) asin(x)cos(x) acos(x)tan(x) atan(x)sqrt(x) abs(x)exp(x) pow(x, y)log(x) floor(x)log10(x) ceil(x)

6

Hyperbolic functions: cosh(x), sinh(x), tanh(x)

See Appendix Dfor other mathfunctions andother libraries.

sqrt(<0) nan -1.#INDpow(x, 1/3)efficiency –Asgn 2: quadratic

Page 7: 1 Operations 4 & Section 5.2 Chapter 4 & Section 5.2

Using <cmath> Using <cmath> functionsfunctions

int main()

{

cout << "\nEnter base and exponent: ";

double base, exponent;

cin >> base >> exponent;

double result = pow(base, exponent);

cout << base << " raised to the power "

<< exponent << " is " << result << endl;

}7

#include <iostream>

#include <cmath>

using namespace std;

C++ libraries whose namesstart with 'c' are C libraries.Their C-names do not havethe 'c' but have .h appended;

e.g., <math.h>

Essentiallysame as '\n'

Page 8: 1 Operations 4 & Section 5.2 Chapter 4 & Section 5.2

Precedence Precedence ( or ( or prioritypriority))

Issue: Is the value of the expression2 + 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 = 2pow(a, 2) + b * c -> 72a/b+c -> 4 a/(b+c_ -> 1

Page 9: 1 Operations 4 & Section 5.2 Chapter 4 & Section 5.2

AssociativityAssociativity

Does the expression8 - 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.

9

Most of the C++ operators that we use associate left.

See Appendix C for a complete list.int a = 8, b = 4, c = 2a – b + c a / b*c

See

App. D

Page 10: 1 Operations 4 & Section 5.2 Chapter 4 & Section 5.2

AssignmentAssignment

The rightmost = is applied first, assigning z zero, then y is assigned the value of z (0),

10

w = x = y = z = 0 ;

then x is assigned the value of y (0), and finally w is assigned the value of x (0).

Assignment is one operator that is right-associative, which allows expressions like:

int w, x, y, z;

w = x = y = z = 0;

Mixed-mode assignments convert the value to type of variable and assign it.

( ) ( ) ( )

double pi = 3.1416; int w = pi; 3 ; pi = w 3.0y = 2*(x = a + b) + c

Page 11: 1 Operations 4 & Section 5.2 Chapter 4 & Section 5.2

Assignment ShortcutsAssignment 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: // add x to var

// sub y from var

var += x;

var -= y;

11

Watchout!

x += 2; x =+2;Don’t use?

Page 12: 1 Operations 4 & Section 5.2 Chapter 4 & Section 5.2

In GeneralIn General

Most arithmetic expressions of the form:

var = var value;

can be written in the "shortcut" form:var = value;

Examples:double x, y;

cin >> x >> y;

// double x’s value

// decrease y by half

x *= 2.0;

y /= 2.0; 12

Page 13: 1 Operations 4 & Section 5.2 Chapter 4 & Section 5.2

Increment and Increment and DecrementDecrement

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: // add 1 to var

// sub 1 from var

var++;

++var;

var--;

--var;

13

Integer variables

only!

Page 14: 1 Operations 4 & Section 5.2 Chapter 4 & Section 5.2

Prefix vs. PostfixPrefix vs. Postfix

As long as the increment (or decrement) operator is used as a separate statement:

int y = 0, x = 0;

. . .

++x; // x becomes

y++; // y becomes

it makes no difference which version is used. 14

1

1

Page 15: 1 Operations 4 & Section 5.2 Chapter 4 & Section 5.2

However, ++ and -- can be used withinother 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; //

The prefix decrement -- behaves similarly.

15

2 1 is displayed

Page 16: 1 Operations 4 & Section 5.2 Chapter 4 & Section 5.2

The postfix form of increment produces the original (unincremented) value as its result:

int x, y = 0;

x = 2 * (y++);

cout << x << " " << y; //

The prefix decrement -- behaves similarly.

0 1 is displayed

16

Page 17: 1 Operations 4 & Section 5.2 Chapter 4 & Section 5.2

I/OI/O

17

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 byoperators >> and <<:

input_stream >> variable

output_stream << expression.

printf, scanf

Page 18: 1 Operations 4 & Section 5.2 Chapter 4 & Section 5.2

18

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 alsoproduce a value.cin >> variable returns ____ as its

value;cout << expression returns _____ as

its value.

cincout

Use at end of course

Page 19: 1 Operations 4 & Section 5.2 Chapter 4 & Section 5.2

19

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 >> and << and both are ___-associative.

Why???

left

skim

Page 20: 1 Operations 4 & Section 5.2 Chapter 4 & Section 5.2

20

Example:

cout << "Width =" << width << " ft.\n";

(cout << "Width =") << width << " ft.\n";

____ << width << " ft.\n";

(cout << width) << " ft.\n";

____ << " ft.\n";

____

cout

cout

cout;Width = 8.5 ft.

skim

Page 21: 1 Operations 4 & Section 5.2 Chapter 4 & Section 5.2

Relational OperationsRelational Operations

x == y x != y

x < y x >= y

x > y x <= y

21

C++ provides six operators for comparisons.Each has two operands and produces a bool value (true or false):

Warning: 1 < x < 2

boolean expressionsChap. 5: prep. for controllist on board

§5.2

Page 22: 1 Operations 4 & Section 5.2 Chapter 4 & Section 5.2

22

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 trueFor 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).

dec, oct, hex

Page 23: 1 Operations 4 & Section 5.2 Chapter 4 & Section 5.2

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.

One of the easiest mistakes to make in C++ is usingin place of == (equality).

See the program on Slide #24.

23

= (assignment)

Page 24: 1 Operations 4 & Section 5.2 Chapter 4 & Section 5.2

#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";}}

24

Executions:

Enter an integer: 99Yes

Enter an integer: -99Yes

Enter an integer: 0Yes

With change:

if (x if (x == 99) 99)

Enter an integer: 99

Yes

Enter an integer: -99

No

Enter an integer: 0

No

Page 25: 1 Operations 4 & Section 5.2 Chapter 4 & Section 5.2

//-- 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;; }}

25

Execution:

0 0

0.1 0.104873

0.2 0.218968

. . .

49.9998 42.937

50.0998 45.782650.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 36.9654

49.8998 39.9954

49.9998 42.937

or

abs(x - 50) >= 1E-10

Page 26: 1 Operations 4 & Section 5.2 Chapter 4 & Section 5.2

PreconditionsPreconditions

Sometimes values must satisfy certain requirements for a program to process them (e.g., they must be positive).

if statement later

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.

e.g., Project 2.3

26Proj. 2 b^2 > 4acProj. 3: payment > purchase

Page 27: 1 Operations 4 & Section 5.2 Chapter 4 & Section 5.2

AssertionsAssertions#include <iostream>

using namespace std;int main(){ cout << "\nEnter the current month number: "; int month; cin >> month; assert(month >= 1); assert(month <= 12);

27

#include <cassert>

// ...}assert() will halt the program if month < 1 or month > 12 and display a message. assert1

Page 28: 1 Operations 4 & Section 5.2 Chapter 4 & Section 5.2

NOTE

Logical OperatorsLogical 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

Example:cin >> month;

28

assert(1 <= month && month <= 12);

NOT: assert(1 <= month <= 12);

assert1

Page 29: 1 Operations 4 & Section 5.2 Chapter 4 & Section 5.2

#include <iostream>using namespace std;

int main(){ bool input1, input2, output; cout << "Enter inputs: "; cin >> input1 >> input2;

output = (input1 || input2) && !(input1 && input2); cout << "Output for inputs " << input1 << " and " << input2 << " is " << output << '\n';}

29

Executions:

Enter inputs: 0 1Output for inputs 0 and 1 is 1

Enter inputs: 1 1Output for inputs 1 and 1 is 0

With change:

cout << "Output for inputs " << boolalpha << input1

<< " and " << input2 << " is " << output << '\n';

Enter inputs: 0 1Output for inputs false and true is true

With change: cin >> boolalpha >> input1 >> input2;

Enter inputs: false true

Output for inputs false and true is true

Binary Half-Adder: (§5.3)Full Adder: (ProgrammingProblems)

XOR circuit

Page 30: 1 Operations 4 & Section 5.2 Chapter 4 & Section 5.2

Character FunctionsCharacter FunctionsThe library <cctype> contains an assortment of boolean character-processing functions:

isalpha(ch) isalnum(ch)

isdigit(ch) iscntrl(ch)

islower(ch) isupper(ch)

isspace(ch) ispunct(ch)

isprint(ch) isgraph(ch)

and two case-conversion functions:toupper(ch) tolower(ch)

30

SeeApp. D

Page 31: 1 Operations 4 & Section 5.2 Chapter 4 & Section 5.2

Write an assertion that will halt the program if a char object named ch is not an uppercase letter:

31

Write an assertion that will halt the program if ch is not one of 'A' through 'G':

assert('A' <= ch && ch <= 'G');

assert('A' <= ch && ch <= 'Z'); oror assert(isupper(ch));

Examples:Examples:

use later - menu

Page 32: 1 Operations 4 & Section 5.2 Chapter 4 & Section 5.2

Operator PrecedenceOperator Precedence( ) HIGHER

+ (positive), - (negative), ! (NOT)

*, /, %

+ (addition), - (subtraction)

<, <=, >, >=

<<, >>

==, !=

&&

||

= LOWER

See Appendix C for a complete list.

54 operators18 precedence

levels

32

When in doubt,use parentheses!

Page 33: 1 Operations 4 & Section 5.2 Chapter 4 & Section 5.2

Operator Associativity Overloadable Arity Description :: right no unary global scope :: left no binary class scope . left no binary direct member selection - left yes binary indirect member selection [] left yes binary subscript (array index) () left yes n/a function call () left yes n/a type construction sizeof right n/a unary size (in bytes) of an object or

type ++ right yes unary increment -- right yes unary decrement ~ right yes unary bitwise NOT ! right yes unary logical NOT + right yes unary plus (sign) - right yes unary minus (sign) * right yes unary pointer dereferencing & right yes unary get address of an object new right yes unary memory allocation

delete right yes unary memory deallocation

() right yes binary type conversion (cast)

. left no binary direct member pointer selection

-> left yes binary indirect member pointer selection

* left yes binary multiplication/ left yes binary division% left yes binary modulus

(remainder)+ left yes binary addition- left yes binary subtraction<< left yes binary bit-shift left>> left yes binary bit-shift right< left yes binary less-than<= left yes binary less-than-or-equal> left yes binary greater-than>= left yes binary greater-than-or-

equal== left yes binary equality!= left yes binary inequality& left yes binary bitwise AND^ left yes binary bitwise XOR| left yes binary bitwise OR&& left yes binary logical AND|| left yes binary logical OR? : left no ternary conditional

expression= right yes binary assignment+= right yes binary addition-

assignment shortcut-= right yes binary subtraction-

assignment shortcut*= right yes binary multiplication-

assignment shortcut/= right yes binary division-assignment

shortcut%= right yes binary modulus-

assignment shortcut&= right yes binary bitwise-AND-

assignment shortcut|= right yes binary bitwise-OR-

assignment shortcut^= right yes binary bitwise-XOR-

assignment shortcut<<= right yes binary bitshift-left-

assignment shortcut>>= right yes binary bitshift-right-

assignment shortcutthrow right yes unary throw an exception, left yes binary expression

separation