Chapter 6 Mathematical Operations C LEARN BY DOING

Chapter 6 Mathematical Operations C++: LEARN BY DOING Todd Breedlove Troy Scevers Randal L. Albert

6. 1 Mathematical Expressions – Programming Differences •

6. 1 Mathematical Expressions - Definitions • l-value • Refers to what can be placed on the left of the assignment operator • Constants and literals cannot be a l-value • r-value • Refers to what can be placed on the right of the assignment operator • Binary and Unary operators • Binary operator has two operands, while a unary operator has a single operand • Widening conversion • Any value can automatically be stored in a variable with a large enough data type

6. 1 Mathematical Expressions – Tips • Do not store a floating point number (decimal) in an integer • They have two different memory representations • Rule of thumb • Match the l-value with the r-value

6. 2 Assignment Operator • Replaces value on the left with the value on the right • Value in var_a is replaced with a zero var_a = 0; • All three variables’ values will be replaced with a 1 • Stylistically, avoid this type of statement var_a = var_b = var_c = 1; • Value in var_a is replaced with the value in var_b var_a = var_b;

6. 3 Standard Arithmetic Operators – Operators Operator Type + – – * / % Binary Unary Binary Description Addition a Subtraction a Negation (changes sign of value) a Multiplication a a Division Modulus (remainder of dividing right operand into left operand) a Example = = = b + b – –b; b * b / b % 5; 5; 5;

6. 3 Standard Arithmetic Operators – Modulus • Both operands of the modulus operator ( % ) must be integers • Modulus operator often causes confusion in beginning programmers • Following results in value of 2 being stored in var_a = 5 % 3;

6. 3 Standard Arithmetic Operators – Division • When doing division pay attention to the data types of the operands • Examples x = 5 / 9; x = 5. 0 / 9. 0; x = 5. 0 F / 9. 0 F; • First example performs integer division resulting in a zero being stored in x • Second example does floating point division resulting in a double • Third example does floating point division resulting in a float

6. 4 Increment and Decrement Operators – Definition • The increment ( ++ ) and decrement ( -- ) operators are unary operators • Add one to the operand subtract one from the operand • Can be expanded as shown below ++int_exp; // pre-increment operator int_exp = int_exp + 1;

6. 4 Increment and Decrement Operators – Pre and Post • Can be placed before or after the operand int_exp = 0; ++int_exp; cout << int_exp << endl; // Displays a 1 int_exp++; cout << int_exp << endl; // Displays a 2 • Pre- and post-increment and decrement operators • No differences as standalone statements

6. 4 Increment and Decrement Operators – Embedded Example • When embedded, pre- and post-increment and decrement operators behave differently int_exp = 0; cout << ++int_exp << endl; // Displays a 1 cout << int_exp++ << endl; // Displays a 1 cout << int_exp << endl; // Displays a 2 • Pre-operators change the value of the operand first and that value is used • Post-operators use the value first and then change it

6. 5 Compound Assignment Operators – Definition • Provide a shorthand notation for manipulating the value stored in a variable • Following statement is common a = a + 2; • Written using compound assignment operators a += 2;

6. 5 Compound Assignment Operators Operator += -= *= /= %= a a a Statement Expansion += -= *= /= %= a a a 5; a = b +. 1; a = b + c; a = 2; a = + – * / % 5; b; (b +. 1); (b + c); 2; • If the r-value is an expression parenthesis must be used to set the order of precedence as shown in multiplication and division in the table above

6. 6 Accumulators Versus Counters – Definition • Counter • A variable that is incremented • Accumulator • A variable that has a value other than one added to itself • Examples • “Count the number of people in a classroom. ” – use a counter • “What is a student’s accumulated loan debt? ” – use an accumulator

6. 6 Accumulators Versus Counters – Example • Always initialize counters and accumulators to a known value (usually zero) int number_students = 0, student_loan = 0; // Counter number_students = number_students + 1; // or number_students++; // Accumulator student_loan = student_loan + 5000; // or student_loan += 5000;

6. 7 Order of Precedence – Definition • Order of precedence • Established order that must be adhered to when evaluating expressions with multiple operations • The table lists the operators starting with those that will be evaluated first postfix ++, postfix -prefix ++, prefix --, unary *, /, % +, =, *=, /=, %=, +=, -=

6. 7 Order of Precedence – Parentheses • Parentheses used to change which operations are performed first • Too many parentheses clutter up an expression, it is better to break up complicated expressions // Cluttered root = ((-b + sqrt( (b * b) - (4 * a * c)) ) / (2 * a)); //Not cluttered discriminant = b * b - 4 * a * c; denominator = 2 * a; root = (-b + sqrt( discriminant ) ) / denominator;

6. 8 Mathematical Functions – Definition • Function • Refers to a task or job • Function of a waiter is to serve food • In programming, a function is a group of related statements that perform a specific task or job • Parameter • Value passed, or given to a function • Sometimes called an argument • Return • Value given back by a function

6. 8 Mathematical Functions • Some mathematical operations, such as exponentiation, do not have associated operators • Provided as functions in an external header file called <cmath> • When included in an expression, a function is evaluated with the highest level of precedence (i. e. , first)

6. 8. 1 The pow Function – Definition • Exponentiation • Accomplished by using the pow function, the syntax of which is shown below <l-value> = pow( <base>, <power> ); • The above syntax equates to the following mathematical expression lvalue = basepower • base parameter can be any numeric data type except an int • power parameter can be any numeric data type • Some compilers do support having an int for the base

6. 8. 1 The pow Function – Example #include <iostream> using std: : cout; using std: : endl; #include <cmath> // Needed for pow int main() { const float PI = 3. 141592 F; float radius = 5; double area = 0; area = PI * pow( radius, 2 ); cout << area << "sq. in. " << endl; } return 0; // Output 78. 5398 sq. in.

6. 8. 1 The pow Function – Requirements • The functions in <cmath> do not require the use of namespace statements • Calling or executing a function has a certain amount of cost involved • Multiplying the value by itself is more efficient than calling the pow function

6. 8. 2 The sqrt Function – Definition • The sqrt function finds the square root of its parameter, syntax shown below <float_point_l-value> = sqrt( <float_point_value>); • Expects a floating point value for its parameter and returns a floating point value • Type cast when the square root of integers is required

6. 8. 2 The sqrt Function – Example • An error results if the parameter is a negative number double value = 5; double square_root = 0; square_root = sqrt( value ); cout << "Square root: " << square_root << endl; // Output Square root: 2. 23607

6. 8. 3 The abs function – Definition • Returns absolute value of the parameter passed <numeric_l-value> = abs( <numeric_r-value> ); double value = -5; double square_root = 0; // Notice the nested function square_root = sqrt ( abs ( value ) ); cout << "Square root: " << square_root << endl; // Output Square root: 2. 23607

6. 8. 3 Some Additional Mathematical Functions Function Description sin Returns a floating point value which is the sine of the floating point parameter. cos Returns a floating point value which is the cosine of the floating point parameter. tan Returns a floating point value which is the tangent of the floating point parameter. asin ceil Returns a floating point value which is the arcsine of the floating point parameter. Returns a floating point value which is the natural log of the floating point parameter. Returns the smallest integer greater than or equal to the floating point parameter. floor Returns the largest integer less than or equal to the floating point parameter. log • The trigonometry function parameters are specified in radians.

6. 9 Type Casting – Definition and Example • Type casting • Explicitly converting a value from one type to another • Converting the return value of pow from a double to an integer double base = 5; int squared = 0; // Type casting return of pow to an integer squared = static_cast<int>( pow ( base, 2 ) ); cout << "Squared: " << squared << endl; // Output Squared: 25

6. 9 Type Casting – Additional Example • Notice the conversion of the variable val from an integer to a character, the character represented by the ASCII value float score = 0; double rvalue = 71. 5; char grade = '