Presentation is loading. Please wait.

Presentation is loading. Please wait.

1 Operations Chapter 4 & Section 5.2. 2 Expressions As we've seen, in a C++ program, any finite sequence of objects and operations that combine to produce.

Similar presentations


Presentation on theme: "1 Operations Chapter 4 & Section 5.2. 2 Expressions As we've seen, in a C++ program, any finite sequence of objects and operations that combine to produce."— Presentation transcript:

1 1 Operations Chapter 4 & Section 5.2

2 2 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; ?

3 Numeric Expressions C++ provides four familiar arithmetic operators: + for performing addition - for performing subtraction * for performing multiplication / for performing division integer () [or character ()] operands Each can be applied to either real ( double ) or integer ( int ) [or character ( char )] operands. 3 C++ provides more than 50 operations (See Appendix C)

4 4 Division However, / behaves differently for than for operands: However, / behaves differently for int than for double operands:     Type of Operands Kind of Division Performed int 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 = ____.

5 56 / 10 = 56 % 10 = 1 / 2 = 1 % 2 = 2 / 3 = 2 % 3 = 5 456 / 100 = 456 % 100 = More examples: 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/3.0  9.0/3.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

6 Numeric Functions The library 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 D for other math functions and other libraries.

7 Using functions 7 #include ________________________ using namespace std; int main() { cout << "\nEnter base and exponent: "; double base, exponent; cin >> base >> exponent; double result = ________________________ ; cout << base << " raised to the power " << exponent << " is " << result << endl; } C++ libraries whose names start with 'c' are C libraries. Their C-names do not have the 'c' but have.h appended; e.g., Essentially same as '\n'

8 Precedence Issue: Is the value of the expression 2 + 3 * 4 (2 + 3) * 4 24 or 2 + (3 * 4) 14 ? (2 + 3) * 4  24 or 2 + (3 * 4)  14 ? Operator __________________ governs evaluation order. * has higher precedence than +, so it is applied first, making the answer ______. 8

9 Associativity Does the expression 8 - 4 - 2 evaluate (8 - 4) - 2 2 or 8 - (4 - 2) 6 ? evaluate (8 - 4) - 2  2 or 8 - (4 - 2)  6 ? Precedence doesn’t help us. Associativity does. Since - is ___________________, the left - is evaluated first. Most C++ operators that we use associate left. See Appendix C for a complete list. 9

10 Assignment Assignment is one operator that is right- associative, which allows expressions like: int w, x, y, z; ____________________________ 10 The rightmost = is applied first, assigning z zero, then y is assigned the value of z (0), 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 operator returns the value being assigned. Mixed-mode assignments convert the value to type of variable and assign it.

11 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: _______________ _______________ ; // add x to var _______________ _______________ ; // sub y from var 11

12 In 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 12

13 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: ____________ ____________ ; // add 1 to var _____________; ____________ ____________ ; // sub 1 from var ____________ ____________ ; 13 Integer variables only!

14 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 ____ y++; // y becomes ____ it makes no difference which version is used. 14 

15 15 If the increment operator is used within another expression, 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. 2 1 is displayed  

16 16 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 

17 I/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 by ____________ >> and << : input_stream >> variable output_stream << expression.

18 18 But these are _____________. Because >> and << are operators, these i/o expessions must also produce a ___________. cin >> variable returns ______ as its value; cout << expression returns _______ as its value. 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.

19 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???

20 20 Example: cout << "Width =" << width << " ft.\n"; _cout << "Width ="_ << width << " ft.\n"; ______ << width << " ft.\n"; _cout << width_ << " ft.\n"; ______ << " ft.\n"; ______; Width = 8.5 ft.

21 Relational Operations C++ provides six operators for comparisons. Each has two operands and produces a _______ value (___________________): x == y x != y x = y x > y x <= y 21 Warning: 1 < x < 2

22 22 C, the parent language of C++, has no bool type. Instead, it uses _____ to represent false and ______________ 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_____________ 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).

23 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 using __________________ in place of ________________ See the program on Slide #24. 23

24 #include 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: 99 Yes Enter an integer: -99 Yes Enter an integer: 0 Yes With change: if (x 99) if (x == 99) Enter an integer: 99 Yes Enter an integer: -99 No Enter an integer: 0 No

25 //-- Effect of roundoff error #include #include using namespace std; int main() { for (float x = 0; ; x = x + 0.1) for (float x = 0; x != 50.0; x = x + 0.1) { float y = x * sqrt(1 + sin(x)); float y = x * sqrt(1 + sin(x)); cout << x << " " << y << endl;; cout << x << " " << y << endl;; }} 25 Execution: 0 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) Enter an integer: 1 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

26 Preconditions Sometimes values must satisfy certain requirements for a program to process them (e.g., they must be positive). Sometimes values must satisfy certain requirements for a program to process them (e.g., they must be positive). Such requirements are called preconditions or _______________. 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 mechanism. A convenient way to check preconditions is to use C++’s assert() mechanism. if statement later e.g., Project 2.3 26

27 Assertions #include #include _________________ using namespace std; int main() { cout << " \nEnter the current month number: " ; int month; cin >> month; _______________________________________; //... } will halt the program if assert() will halt the program if month 12 and display a message. 27

28 NOTE 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 falseExample: cin >> month; ______________________________________ 28 NOT: assert(1 <= month <= 12);

29 #include #include using namespace std; int main() { bool input1, input2, output; bool input1, input2, output; cout << "Enter inputs: "; cout << "Enter inputs: "; cin >> input1 >> input2; cin >> input1 >> input2; output = (input1 || input2) && !(input1 && input2); output = (input1 || input2) && !(input1 && input2); cout << "Output for inputs " << input1 cout << "Output for inputs " << input1 << " and " << input2 << " is " << output << '\n'; << " and " << input2 << " is " << output << '\n';} 29 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 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 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: (Programming Problems)

30 Character Functions The library 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 See App. D

31 Examples: 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'); or or assert(isupper(ch));

32 Operator Precedence HIGHER ( ) HIGHER (positive), (negative), (NOT) + (positive), - (negative), ! (NOT),, *, /, % (addition), - (subtraction) + (addition), - (subtraction),,,, >= >, ==, != && || LOWER = LOWER See Appendix C for a complete list. 54 operators 18 precedence levels 32 When in doubt, use parentheses!


Download ppt "1 Operations Chapter 4 & Section 5.2. 2 Expressions As we've seen, in a C++ program, any finite sequence of objects and operations that combine to produce."

Similar presentations


Ads by Google