Chapter 6 Mathematical Operations. 6.1 Mathematical Expressions In mathematics this expression is valid 0 = -4y + 5 It is invalid in programming Left.

Slides:



Advertisements
Similar presentations
Arithmetic Calculations
Advertisements

Types and Arithmetic Operators
Chapter 3: Expressions and Interactivity. Outline cin object Mathematical expressions Type Conversion and Some coding styles.
Copyright 2004 Scott/Jones Publishing Alternate Version of STARTING OUT WITH C++ 4 th Edition Chapter 3 Expressions.
Chapter 3 Assignment and Interactive Input. 2 Objectives You should be able to describe: Assignment Operators Mathematical Library Functions Interactive.
Copyright © 2012 Pearson Education, Inc. Chapter 3: Expressions and Interactivity.
COMPSCI 125 Spring 2005 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 3: Numeric Data *Variables *Numeric data.
© Janice Regan, CMPT 102, Sept CMPT 102 Introduction to Scientific Computer Programming Expressions and Operators Program Style.
Data types and variables
Expressions An expression is a sequence of operands and operators that reduces to a single value expression operator operand An operator is a language-specific.
Chapter 2 Data Types, Declarations, and Displays
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 3: Expressions and Interactivity.
Data Types, Expressions and Functions (part I)
Performing Computations C provides operators that can be applied to calculate expressions: example: tax is 8.5% of the total sale expression: tax =
Basic Elements of C++ Chapter 2.
What is a variable?  A variable holds data in memory so the program may use that data, or store results.  Variables have a data type. int, boolean, char,
C++ Operators CS242 COMPUTER PROGRAMMING T.Banan Al-Hadlaq.
1 Chapter Two Using Data. 2 Objectives Learn about variable types and how to declare variables Learn how to display variable values Learn about the integral.
Chapter 2 Data Types, Declarations, and Displays.
Expressions and Interactivity Chapter 3. 2 The cin Object Standard input object Like cout, requires iostream file Used to read input from keyboard Often.
Operaciones y Variables
CHAPTER:8 OPERATORS AND EXPRESSION IN C++ Prepared By Prepared By : VINAY ALEXANDER ( विनय अलेक्सजेंड़र ) PGT(CS),KV JHAGRAKHAND.
Chapter 2 part #4 Operator
Chapter 3 COMPLETING THE BASICS Programming Fundamentals with C++1.
Object-Oriented Programming Using C++ Third Edition Chapter 2 Evaluating C++ Expressions.
Numeric Types, Expressions, and Output ROBERT REAVES.
Chapter 3 Processing and Interactive Input. 2 Assignment  The general syntax for an assignment statement is variable = operand; The operand to the right.
CNG 140 C Programming Lecture Notes 2 Processing and Interactive Input Spring 2007.
Basic Notions Review what is a variable? value? address? memory location? what is an identifier? variable name? keyword? what is a legal identifier? what.
LESSON 6 – Arithmetic Operators
CHAPTER 2 PART #4 OPERATOR 2 nd semester King Saud University College of Applied studies and Community Service Csc 1101 By: Asma Alosaimi Edited.
OPERATORS.
Chapter 3 Assignment, Formatting, and Interactive Input C++ for Engineers and Scientists Third Edition.
Operators Precedence - Operators with the highest precedence will be executed first. Page 54 of the book and Appendix B list C's operator precedence. Parenthesis.
Chapter 3: Assignment, Formatting, and Interactive Input.
C++ for Engineers and Scientists Second Edition Chapter 3 Assignment, Formatting, and Interactive Input.
CHAPTER 1.3 THE OPERATORS Dr. Shady Yehia Elmashad.
C++ Programming Lecture 9 Functions – Part I By Ghada Al-Mashaqbeh The Hashemite University Computer Engineering Department.
Chapter 3 – Variables and Arithmetic Operations. Variable Rules u Must declare all variable names –List name and type u Keep length to 31 characters –Older.
Expressions and Interactivity. 3.1 The cin Object.
Programming Fundamentals with C++1 Chapter 3 COMPLETING THE BASICS.
Recap……Last Time [Variables, Data Types and Constants]
Programming Fundamentals. The setw Manipulator setw changes the field width of output. The setw manipulator causes the number (or string) that follows.
Lecture 5: Expressions and Interactivity Professor: Dr. Miguel Alonso Jr. Fall 2008 CGS2423/COP1220.
Chapter 7 Conditional Statements. 7.1 Conditional Expressions Conditions - compare the values of variables, constants and literals using one or more relational.
ECE 103 Engineering Programming Chapter 4 Operators Herbert G. Mayer, PSU CS Status 6/19/2015 Initial content copied verbatim from ECE 103 material developed.
STRUCTURED PROGRAMMING C++ Operators. Content 2  C++ operators  Assignment operators  Arithmetic operators  Increment and decrement operators  Decision.
Programming Fundamentals. Summary of Previous Lectures Phases of C++ Environment Data Types cin and cout.
Chapter 7 Conditional Statements. 7.1 Conditional Expressions Condition – any expression that evaluates to true/false value Relational operators are BINARY.
Chapter INTRODUCTION Data Types and Arithmetic Calculations.
SCP1103 Basic C Programming SEM1 2010/2011 Arithmetic Expressions Week 5.
ECE 103 Engineering Programming Chapter 4 Operators Herbert G. Mayer, PSU Status 6/10/2016 Initial content copied verbatim from ECE 103 material developed.
Variables, Operators, and Expressions
Lecture 3 Expressions, Type Conversion, Math and String
Chapter Topics The Basics of a C++ Program Data Types
Chapter 7: Expressions and Assignment Statements
Chapter 3 Assignment and Interactive Input.
INSPIRING CREATIVE AND INNOVATIVE MINDS
TMF1414 Introduction to Programming
Relational Operations
Chapter 7: Expressions and Assignment Statements
Arithmetic & other operations
Operators and Expressions
Arithmetic Operator Operation Example + addition x + y
Expressions and Interactivity
Basic Notions Review what is a variable? value? address? memory location? what is an identifier? variable name? keyword? what is legal identifier? what.
Expressions Chapter 4 Copyright © 2008 W. W. Norton & Company.
Doing Arithmetic Today’s lecture is in chapter 2 Assignment statement:
OPERATORS AND EXPRESSIONS IN C++
Operator King Saud University
Presentation transcript:

Chapter 6 Mathematical Operations

6.1 Mathematical Expressions In mathematics this expression is valid 0 = -4y + 5 It is invalid in programming Left side of the assignment operator ( = ) must be a variable All operations must be explicitly specified There is only one way to specify multiplication in C++ ( * )

6.1 Mathematical Expressions 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

6.1 Mathematical Expressions Binary operator - has two operands Unary operator - has one operand Widening conversion - any value can automatically be stored in a variable with a large enough data type

6.1 Mathematical Expressions 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 Op’s ( +, -, *, /, % ) Mathematical operators available in C++ OperatorTypeDescriptionExample + BinaryAddition a = b + 5; – BinarySubtraction a = b – 5; – Unary Negation (changes sign of value) a = –b; * BinaryMultiplication a = b * 5; / BinaryDivision a = b / 5; % Binary Modulus (remainder of dividing right operand into left operand) a = b % 5;

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 var_a = 5 % 3; 6.3 Standard Arithmetic Op’s (+, -, *, /, %)

When doing division pay attention to the data types of the operands Examples: x = 5 / 9; x = 5.0 / 9.0; x = 5.0F / 9.0F; First example - performs integer division resulting in a zero being stored in x

6.3 Standard Arithmetic Op’s ( +, -, *, /, % ) Examples: x = 5 / 9; x = 5.0 / 9.0; x = 5.0F / 9.0F; Second example does floating point division resulting in a double Example three does floating point division resulting in a float

6.4 Increment and Decrement Op’s ( ++,-- ) The increment ( ++ ) and decrement ( -- ) operators are unary operators Add one to the operand and 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 Op’s ( ++,-- ) Can be placed before or after the operand int int_exp = 0; ++int_exp; // Pre-increment operator cout << int_exp << endl; // Displays a 1 int_exp++; // Post-increment operator cout << int_exp << endl; // Displays a 2 Pre- and post-increment and decrement operators: No differences as standalone statements

6.4 Increment and Decrement Op’s ( ++,-- ) When embedded, pre- and post-increment and decrement operators behave differently int 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 Assign. Op’s (+=, –=, *=, /=, %=) 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 Assign. Op’s ( +=, –=, *=, /=, %= ) OperatorStatementExpansion +=a += 5;a = a + 5; -=a -= b;a = a – b; *=a *= b +.1;a = a * (b +.1); /=a /= b + c;a = a / (b + c); %=a %= 2;a = a % 2; Notice the expansions of the subtraction and division compound assignment operators require parentheses to achieve the same result

6.6 Accumulators Versus Counters 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 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 ; // or student_loan += 5000;

6.7 Order of Precedence 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 used to change which operations are performed first Too many parentheses clutter up an expression - 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 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

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

6.8.1 The pow Function Exponentiations - accomplished by using the pow function, the syntax of which is shown below = pow(, ); The above syntax equates to the following mathematical expression lvalue = base power

6.8.1 The pow Function 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 (those that are less compliant with the current standard)

6.8.1 The pow Function #include using std::cout; using std::endl; #include // Needed for pow int main() { const float PI = F; float radius = 5; double area = 0; area = PI * pow( radius, 2 ); cout << area << " sq. in." << endl; return 0; }

6.8.1 The pow Function The functions in 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 The sqrt function finds the square root of its parameter - syntax shown below = sqrt( ); 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 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;

6.8.3 The abs function Returns absolute value of the parameter passed = abs( ); double value = -5; double square_root = 0; // Notice the nested function square_root = sqrt( abs( value ) ); cout << "Square root: " << square_root << endl;

6.8.3 The abs Function Some additional mathematical functions FunctionDescription sinReturns 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 Returns a floating point value which is the arcsine of the floating point parameter log Returns a floating point value which is the natural log of the floating point parameter ceilReturns smallest integer greater than or equal to the floating point parameter floorReturns largest integer less than or equal to the floating point parameter

6.9 Type Casting 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; squared = static_cast ( pow( base, 2 )); cout << "Squared: " << squared << endl;

6.9 Type casting 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 = '\0'; int val = 67; score = static_cast ( rvalue ); grade = static_cast ( val ); cout << "Score: " << score << '\n' << "Grade: " << grade << endl;

6.9 Type Casting Other forms of type casting that, while common, should be avoided (unless writing a C program) score = (float)rvalue; score = float(rvalue);

6.11 C – The Differences Use instead of The pow and sqrt functions always are passed a double and return a double

6.11 C – The Differences FunctionData Type absint fabsdouble labslong Absolute values are calculated by the use of three different functions depending upon the data type of the parameter

6.11 C – The Differences Type casting uses one of the alternate styles previously discussed double y = 5.0; float x = static_cast ( y ); // C++ type casting float x = (float)y; // C type casting