Presentation is loading. Please wait.

Presentation is loading. Please wait.

Operations and Expressions. Computer Programming 2 Objectives Detailed look at numeric operations Work with bool expressions Consider the processing of.

Similar presentations


Presentation on theme: "Operations and Expressions. Computer Programming 2 Objectives Detailed look at numeric operations Work with bool expressions Consider the processing of."— Presentation transcript:

1 Operations and Expressions

2 Computer Programming 2 Objectives Detailed look at numeric operations Work with bool expressions Consider the processing of characters Study assignment operator Use increment, decrement operators User-defined operators

3 Computer Programming 3 Expressions Definition: any sequence of objects (E.g. literals and variables) and operations that combine them to produce a value is called an expression. Example: double pressure = ((depth / FEET_PER_ATM) + 1) * LBS_PER_SQ_IN_PER_ATM;

4 Computer Programming 4 Operations Arithmetic/numeric operations (for real numbers and/or integers) – +, -, /, %, *, --, ++ Logic operations (for Booleans) – &&, ||, ! Relational/comparison operations (for comparing expressions) – ==, !=,, = Bitwise operations (for manipulating bits) – &, |, >>, <<

5 Computer Programming 5 Arithmetic/Numeric Expressions C++ provides four familiar arithmetic operators: – + for performing addition – - for performing subtraction – * for performing multiplication – / for performing division Each of these four can be applied to either real ( double ) or integer ( int ) operands.

6 Computer Programming 6 Division Division behaves differently for int and double operands – Note the results of the following 3/4  03.0/4.0  0.75 3.0/4  0.753/4.0  0.75 If both operands are integers – Integer division performed – Otherwise real division performed

7 Computer Programming 7 Integer vs. Real Division Recall division from grade school. – Teacher: “4 goes into 3 how many times?” – Pupils: “0 times with a remainder 4” The expression 3 / 4 returns the quotient. – This is integer division The expression 3 % 4 returns the remainder. – This is read, "3 mod 4"

8 Computer Programming 8 Type Conversions Combining an int and a real in the same expression – 2 + 3.0  5.0 C++ automatically converts narrow values into wider values – An integer is converted to a real – Result of the expression is a real Often called "promotion"

9 Computer Programming 9 Precedence Consider the possible 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 + * is applied first

10 Computer Programming 10 Operator Precedence () HIGHER + (positive), - (negative), ! (NOT) *, /, %, >= ==, != && || LOWER See Appendix C for a complete list...

11 Computer Programming 11 Associativity Consider the possible value of the expression 8 - 4 - 2 (8 - 4) - 2  4 or 8 - (4 - 2)  6 Precedence doesn’t help us Associativity tells us. – Subtraction is left-associative, the left - is evaluated first, giving us 4. Most (but not all) C++ operators associate left. – See Appendix C in the text for a complete list...

12 Computer Programming 12 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) log10(x) log(x) pow(x, y) floor(x) ceiling(x) abs(x)

13 Computer Programming 13 Using functions #include using namespace std; 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; return 0; }

14 Computer Programming 14 Type Conversions Possible to explicitly convert a value from one type to another Syntax to use: type (expression) or (type) expression Conversion can cause loss of data double x = 3.456; cout << (int) x; What is the output? 3

15 Computer Programming 15 Boolean/logic Expressions C++ type bool has two literals – false and true Relational operators produce boolean expressions

16 Computer Programming 16 Relational Operations Use operators for comparisons – Each takes two operands – Produces a bool value ( true or false ): x == y x != y x = y x > y x <= y Warning: – Do NOT confuse = (assignment) – With == (equality).

17 Computer Programming 17 Logic Expressions Logical operators

18 Computer Programming 18 Logic Expressions More complex boolean expressions can be built using the logical operators: a && b // true iff a, b are both true a || b // true iff a or b is true !a // true iff a is false Example: cin >> score; assert (0 <= score && score <= 100);

19 Computer Programming 19 Short-Circuit Evaluation Consider the boolean expression ( n != 0 ) && ( x < 1.0 / n ) – If n == 0 the right hand expression causes a program crash C++ will evaluate the original expression from left to right – If n == 0, the left expression evaluates false – Since it is an &&, this makes the whole expression false – So, it does not proceed to the right expression

20 Computer Programming 20 Preconditions Definition: When a program makes assumptions about its input values – Example: that they’re positive Preconditions are boolean expressions – Must be true in order for the program to work correctly. To check preconditions, C++ provides the assert() mechanism...

21 Computer Programming 21 Assertions #include using namespace std; int main() { cout << “\nEnter your age: “; int age; cin >> age; assert(age > 0); //... }

22 Computer Programming 22 Character Expressions Character variables can be … – Declared and initialized char middleInitial = 'Q'; – Assigned middleInitial = 'Z'; – Used for I/O cout << middleInitial; cin >> middleInitial; – Compared assert (middleInitial != 'X');

23 Computer Programming 23 Character Functions Boolean character-processing functions found in library: isalpha(ch) isalnum(ch) isdigit(ch) iscntrl(ch) islower(ch) isupper(ch) isspace(ch) ispunct(ch) isprint(ch) isgraph(ch) Case-conversion functions: toupper(ch) tolower(ch)

24 Computer Programming 24 Assignment Syntax: variable = expression; – Expression is evaluated – Value placed in memory location associated with variable Example: xCoord = 4.56; code = 'T';

25 Computer Programming 25 Given the sequence of three assignment statements, note the results Note that previous variable values are gone after execution of assignment Assignment

26 Computer Programming 26 Assignment The assignment operator = – Right-associative, – Supports expressions like: int w, x, y, z; w = x = y = z = 0; The rightmost = is applied first, – assigning z zero, – then y is assigned the value of z (0), – then x is assigned the value of y (0) – finally w is assigned the value of x (0).

27 Computer Programming 27 Assignment Shortcuts Some assignments are so 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

28 Computer Programming 28 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; x *= 2.0; // double x’s value y /= 2.0; // decrease y by half

29 Computer Programming 29 Increment and Decrement Other common assignments include: var = var + 1; // add 1 to var var = var - 1; // sub 1 from var C++ provides shortcuts for them, too: var++; // add 1 to var var -- ; // sub 1 from var

30 Computer Programming 30 Prefix Increment The prefix form of increment produces the final (incremented) value as its result: int x, y = 0; x = ++y; cout << x; // 1 is displayed The prefix decrement behaves similarly...

31 Computer Programming 31 Postfix Increment The postfix form of increment produces the original (unincremented) value as its result: int x, y = 0; x = y++; cout << x; // 0 is displayed // y now holds value of 1 The prefix decrement behaves similarly...

32 Computer Programming 32 Prefix vs. Postfix So long as the increment (or decrement) operator is used as a separate statement: int y = 0, x = 0; ++x; // x == 1 y++; // y == 1 … it makes no difference which version is used.

33 Computer Programming 33 An expression followed by a semicolon becomes an expression statement – x = y + z; – 'A'; – cos (z); Expressions into Statements – Semicolons This expression statement has the added side effect of changing the value of x

34 Computer Programming 34 I/O Streams C++ has no I/O as part of the language – I/O streams are provided by istream and ostream cout cin

35 Computer Programming 35 Input Expressions Form – input_stream >> variable; May be chained together – cin >> x >> y; Adapts to whatever type variable is – User must enter correct type Best to prompt user for input expected – cout << "Enter choice (1 – 10) : "

36 Computer Programming 36 Output Expressions Form – output_stream << expression; May be chained – cout << "The sum = " << sum; The expression can be a variable, a constant or a combination using operators – cout << "Sum = " << v1 + v2 + v3; The expression adapts to whatever types are used

37 Computer Programming 37 Output Formatting Possible to specify appearance of output – From iostream: showpoint Display decimal point and trailing zeros for all real numbers. noshowpoint Hide decimal point and trailing zeros for whole real numbers (default). fixed Use fixed-point notation for real values. scientific Use scientific notation for real values. boolalpha Display boolean values as strings “true” and “false”. left Display values left justified within a field. right Display values right justified within a field (default). – From iomanip: setw(w) Display the next value in a field of size w (default 1). setprecision(p) Display p fractional digits for all subsequent output of real values (common default is 6). Must specify the proper include files to use these. #include #include using namespace std;

38 Computer Programming 38 User-defined operators Implement the member function operatorXXX – cout << … is the same as cout.operator<<(…) – E.g. operator++, operator--, etc.. class Person { … //instead of say string operator<<(string s) { return s; } }; int main () { Person belaid; cout << (belaid<<“Hello Everyone!”)<<endl; return 0; }

39 Computer Programming 39 General Behavior Problem For energy released, enter mass (Must be non-negative): 123 Energy released = 999.99 units Use Einstein's equation to calculate the amount of energy released by a quantity of mass given in the problem

40 Computer Programming 40 Objects Description Software Objects TypeKindName screen ostream varying cout prompt string constant quantity of matter double varying mass keyboard istream varying cin qty of energy double varying energy descriptive label string constant

41 Computer Programming 41 Operations i. Display a string (the prompt) on the screen ii. Read a nonnegative number ( mass ) from the keyboard iii. Compute energy from mass iv. Display a number ( energy ) and a string on the screen

42 Computer Programming 42 Additional Elements We note that step iii. requires Einstein's equation This implies a few more operations And additional objects v. Exponentiation vi. Multiplication of reals vii. Storage of a real Description Software Objects TypeKindName Speed of light double constant SPEED_OF_LIGHT 2 int constant

43 Computer Programming 43 Algorithm We organize the objects and operations into an algorithm: 1. Declare the constant SPEED_OF_LIGHT. 2. Display to cout a prompt for the mass to be converted into energy. 3. Read a nonnegative number from cin into mass. 4. Compute 5. Display to cout a descriptive label and energy.

44 Computer Programming 44 Coding, Execution, Testing Code the algorithm – Put the algorithm into “C++ words” Compile – Fix syntax errors Execute – Fix runtime errors Test – Fix logic and runtime errors


Download ppt "Operations and Expressions. Computer Programming 2 Objectives Detailed look at numeric operations Work with bool expressions Consider the processing of."

Similar presentations


Ads by Google