<<

UnitUnit 3,3, LessonLesson 33 MathMath Operations,Operations, AssignmentAssignment Operators,Operators, andand ArithmeticArithmetic OperatorsOperators

Mr.Mr. DaveDave ClausenClausen LaLa CañadaCañada HighHigh SchoolSchool AssignmentAssignment OperatorOperator

•• YouYou havehave usedused thethe assignmentassignment operatoroperator (=)(=) toto initializeinitialize variables,variables, soso youyou alreadyalready knowknow mostmost ofof whatwhat therethere isis toto knowknow aboutabout thethe assignmentassignment operatoroperator •• TheThe assignmentassignment operatoroperator changeschanges thethe valuevalue ofof thethe variablevariable toto thethe leftleft ofof thethe operator.operator. •• ForFor example:example: ii == 25;25; //changes//changes thethe valuevalue ofof ii toto 2525

Mr. Dave Clausen 2 CodeCode ListList 33--11 #include#include ////iassign.cppiassign.cpp iassign.txtiassign.txt //declaring//declaring andand initializinginitializing variablesvariables inin twotwo stepssteps intint mainmain ()() {{ int i; // declare i as an integer i=1000; // assign the value 1000 to i cout << i << endl; i=25; // assign the value 25 to i cout << i << endl; return 0; } Mr. Dave Clausen 3 CodeCode ListList 33--22 #include#include ////multint.cppmultint.cpp multint.txtmultint.txt ////declaringdeclaring multiplemultiple variablesvariables inin oneone stepstep //initializing//initializing multiplemultiple variablesvariables inin oneone stepstep intint mainmain ()() {{ int i, j, k; // declare i, j, and k as integers i =j=k=10; //initialize all of the variables to 10 cout << i << ‘\n’; cout << j << ‘\n’; cout << k << ‘\n’; return 0; } Mr. Dave Clausen 4 DeclareDeclare && InitializeInitialize

•• ConstantsConstants MUSTMUST bebe declareddeclared andand initializedinitialized inin thethe samesame statement.statement. •• VariablesVariables MAYMAY bebe declareddeclared andand initializedinitialized inin thethe samesame statement.statement. •• ForFor example:example: intint numbernumber == 10;10; doubledouble resultresult == 0.0;0.0; charchar letterletter == ‘‘ ‘;‘; //// aa spacespace

Mr. Dave Clausen 5 ArithmeticArithmetic OperatorsOperators

•• AA specificspecific setset ofof arithmeticarithmetic operatorsoperators isis usedused toto performperform calculationscalculations inin ++C++ •• TheseThese arithmeticarithmetic operators,operators, shownshown inin TableTable 33--1,1, maymay bebe somewhatsomewhat familiarfamiliar toto youyou •• AdditionAddition andand subtractionsubtraction andand performedperformed withwith thethe familiarfamiliar ++ andand -- operatorsoperators

Mr. Dave Clausen 6 TableTable 33--11

TheThe arithmeticarithmetic operatorsoperators areare usedused withwith twotwo ,operands, asas inin thethe examplesexamples inin TableTable 33--11

Mr. Dave Clausen 7 UsingUsing ArithmeticArithmetic OperatorsOperators ArithmeticArithmetic operatorsoperators areare mostmost oftenoften usedused onon thethe rightright ofof anan assignmentassignment operatoroperator asas shownshown inin thethe examplesexamples inin TableTable 33--22

Mr. Dave Clausen 8 AssignmentAssignment OperatorOperator vs.vs. TheThe EqualEqual SignSign

•• TheThe assignmentassignment operatoroperator (=)(=) functionsfunctions differentlydifferently inin C++C++ fromfrom thethe wayway thethe equalequal signsign functionsfunctions inin Algebra.Algebra. •• LookLook atat thethe followingfollowing statement:statement: xx == xx ++ 10;10; •• ThisThis statementstatement isis FalseFalse inin Algebra.Algebra. •• InIn C++,C++, thethe oldold valuevalue ofof xx isis incrementedincremented byby 1010 andand thenthen assignedassigned toto thethe newnew valuevalue ofof x.x.

Mr. Dave Clausen 9 CodeCode ListList 33--33 // assign.cpp assign.txt #include int main () { int i = 2; //declare and initialize in one step int j = 3; //declare and initialize in one step int k = 4; //declare and initialize in one step int l; float a = 0.5; //declare and initialize in one step float b = 3.0; //declare and initialize in one step float c; 1 = i + 2; cout << 1 << ‘\n’; 1 = 1- j; cout << 1 << ‘\n’; 1 = i * j * k; cout << 1 << ‘\n’; 1 = k / i; cout << 1<< ‘\n’; c = b * a; cout << c << '\n'; c = b / a; cout << c << '\n'; getch(); return 0; } Mr. Dave Clausen 10 ArithmeticArithmetic operatorsoperators areare usedused toto createcreate expressionsexpressions

Expression Result of expression cost = price + tax cost is assigned the value of price plus tax owed = total – discount owed is assigned the value of total minus discount

area = l * w area is assigned the value of l times w one_eighth = 1 / 8 one_eighth is assigned the value of 1 divided by 8

r = 5 % 2 r is assigned the integer remainder of 5 divided by 2 by using the modulus operator x = -y x is assigned the value of -y

Mr. Dave Clausen 11 AssignmentAssignment StatementsStatements

•• AA MethodMethod ofof puttingputting valuesvalues intointo memorymemory locationslocations variablevariable namename == value;value; aa variablevariable namename == expression;expression; •• AssignmentAssignment isis mademade fromfrom rightright toto leftleft •• ConstantsConstants can’tcan’t bebe onon leftleft sideside ofof statementstatement •• ExpressionExpression isis aa constantconstant oror variablevariable oror combinationcombination thereofthereof

Mr. Dave Clausen 12 AssignmentAssignment StatementsStatements

•• ValuesValues onon rightright sideside notnot normallynormally changedchanged •• VariableVariable andand expressionexpression mustmust bebe ofof compatiblecompatible datadata typestypes (more(more later)later) •• PreviousPrevious valuevalue ofof variablevariable discardeddiscarded toto makemake roomroom forfor thethe newnew valuevalue •• ForFor nownow char,char, int,int, andand doubledouble areare compatiblecompatible withwith eacheach otherother

Mr. Dave Clausen 13 AssignmentAssignment ExamplesExamples

•• score1score1 == 72.3;72.3; •• score2score2 == 89.4;89.4; •• score3score3 == 95.6;95.6; •• averageaverage == (score1(score1 ++ score2score2 ++ score3)score3) // 3.03.0 whywhy notnot dividedivide byby 33 insteadinstead ofof 3.0?3.0?

Mr. Dave Clausen 14 TheThe ModulusModulus operatoroperator

• The Modulus Operator, which can be used only for integer , returns the remainder rather than the quotient. • As shown in figure 3-1, integer division is similar to the way you divide manually

Mr. Dave Clausen 15 CodeCode ListList 33--44

// remain.cpp remain.txt // Calculations using assignment statements #include int main () { int dividend, divisor, quotient, remainder; / / ------Input------cout << “Enter the dividend “; cin >> dividend; cout << “Enter the divisor “; cin >> divisor;

/ / ------Calculations------quotient = dividend / divisor; remainder = dividend % divisor;

/ / ------Output------cout << “the quotient is “ << quotient; cout << “ with a remainder of “ << remainder << ‘\n’; return 0; }

Mr. Dave Clausen 16 CodeCode ListList 33--55

// remain2.cpp remain2.txt //calculations in cout statements - while it can be done, please DON’T DO THIS #include int main() { int dividend, divisor;

// ------Input------cout << “enter the dividend”; cin >> dividend; cout << “Enter the divisor”; cin >> divisor;

// ------Calculations in the Output------Don’t Do This For My Class cout << “the quotient is “ << dividend/divisor; cout << “with a remainder of “ << dividend % divisor << ‘\n’; return 0; }

Mr. Dave Clausen 17 IncrementingIncrementing andand DecrementingDecrementing

•• AddingAdding oror subtractingsubtracting 11 fromfrom aa variablevariable isis veryvery commoncommon inin programs.programs. AddingAdding 11 toto aa variablevariable isis calledcalled incrementing,incrementing, andand subtractingsubtracting 11 fromfrom aa variablevariable isis calledcalled decrementing.decrementing.

Mr. Dave Clausen 18 TheThe ++++ andand ---- OperatorsOperators

•• C++C++ providesprovides operatorsoperators forfor incrementingincrementing andand decrementing.decrementing. InIn C++,C++, youyou cancan incrementincrement anan integerinteger variablevariable usingusing thethe ++++ operator,operator, andand decrementdecrement usingusing thethe ---- operator,operator, asas shownshown inin TableTable 33--33

Mr. Dave Clausen 19 CodeCode ListList 33--66

// inc_dec.cpp inc_dec.txt #include int main() { int j; // declare j as int

j=1; // initialize j to 1 cout << “j = “ << j << ‘\n’; j++; //increment j cout << “j = “ << j << ‘\n’; j--; //decrement j cout << “j = “ << j << ‘\n’;

return 0; }

Mr. Dave Clausen 20 VariationsVariations ofof IncrementIncrement andand DecrementDecrement AtAt firstfirst glance,glance, thethe ++++ andand –– operatorsoperators seemseem veryvery simple.simple. ButBut therethere areare twotwo waysways thatthat eacheach ofof thesethese operatorsoperators cancan bebe used.used. TheThe operatorsoperators cancan bebe placedplaced eithereither beforebefore oror afterafter thethe variable.variable. TheThe locationlocation ofof thethe operatorsoperators affectsaffects thethe wayway theythey work.work. c++c++ oror ++c++c cc-- -- oror -- -- cc WeWe willwill useuse c++c++ andand cc-- -- forfor thisthis classclass

Mr. Dave Clausen 21 OrderOrder ofof OperationsOperations

• You may recall from your math classes the rules related to the order in which operations are performed. These rules are called the order of operations. The C++ compiler uses a similar set of rules for its calculations. Calculations are processed in the following order • Minus sign used to change sign (-) • and division (*, /, %) • and (+, -)

•C++ lets you use parentheses to change the order of operations. For example, consider the two statements in Figure 3-2.

Mr. Dave Clausen 22 CodeCode ListList 33--77

/ / order.cpp order.txt #inlcude int main () { int answer

answer = 1 + 2 * 2 + 3; cout << answer << ‘\n’; answer = (1 + 2) * (2 + 3); cout << answer << ‘\n’; answer = 1 + 2 * (2 + 3); cout << answer << ‘\n’; answer = (1 +2) * 2 + 3 ; cout << answer << ‘\n’;

return 0; }

Mr. Dave Clausen 23 IntegerInteger ArithmeticArithmetic

•• ++ AdditionAddition •• -- SubtractionSubtraction •• ** MultiplicationMultiplication •• // QuotientQuotient (Integer(Integer Division)Division) •• %% RemainderRemainder (Modulus)(Modulus) Quotient Remainder Divisor Dividend + Divisor

Mr. Dave Clausen 24 IntegerInteger OrderOrder OfOf OperationsOperations

•• ExpressionsExpressions withinwithin parenthesesparentheses nestednested parentheses:parentheses: fromfrom insideinside outout •• ** (multiplication),(multiplication), %% (modulus),(modulus), // (division)(division) fromfrom leftleft toto rightright •• ++ (addition),(addition), -- (subtraction)(subtraction) fromfrom leftleft toto rightright

Mr. Dave Clausen 25 IntegerInteger ArithmeticArithmetic (Examples)(Examples)

(3(3--4)*54)*5 == --55 33 ** ((--2)2) == --66 1717 // 33 == 55 1717 %% 33 == 22 1717 // ((--3)3) == --55 --1717 %% 77 == --33 --42+50%17=42+50%17= --2626

Mr. Dave Clausen 26 RealReal NumberNumber ArithmeticArithmetic

•• TypeType double:double:

•• ++ AdditionAddition •• -- SubtractionSubtraction •• ** MultiplicationMultiplication •• // DivisionDivision

Mr. Dave Clausen 27 RealReal NumberNumber OrderOrder OfOf OperationsOperations •• ExpressionsExpressions withinwithin parenthesesparentheses nestednested parentheses:parentheses: fromfrom insideinside outout •• ** (multiplication),(multiplication), // (division)(division) fromfrom leftleft toto rightright •• ++ (addition),(addition), -- (subtraction)(subtraction) fromfrom leftleft toto rightright

Mr. Dave Clausen 28 RealReal NumberNumber ArithmeticArithmetic (Examples)(Examples)

2.02.0 ** (1.2(1.2 -- 4.3)4.3) == --6.26.2 2.02.0 ** 1.21.2 -- 4.34.3 == --1.91.9 --12.612.6 // (3.0(3.0 ++ 3.0)3.0) == --2.12.1 3.13.1 ** 2.02.0 == 6.26.2 --12.612.6 // 3.03.0 ++ 3.03.0 == --1.21.2

Mr. Dave Clausen 29 CompoundCompound AssignmentsAssignments •• ““ShortShort hand”hand” notationnotation forfor frequentlyfrequently usedused assignmentsassignments (We(We willwill notnot useuse thesethese forfor readabilityreadability ofof ourour programs.)programs.) Short hand Longer form x += y x = x + y x -= y x = x - y x *= y x = x * y x /= y x = x / y x %= y x = x % y

Mr. Dave Clausen 30 SampleSample ProgramProgram

HereHere isis aa programprogram thatthat printsprints datadata aboutabout thethe costcost ofof threethree textbookstextbooks andand calculatescalculates thethe averageaverage priceprice ofof thethe books:books:

Books.cppBooks.cpp Books.txtBooks.txt

Mr. Dave Clausen 31 InputInput •• CinCin (pronounced(pronounced seesee--in)in) getsgets datadata fromfrom keyboard,keyboard, thethe standardstandard inputinput streamstream extractorextractor operatoroperator >>>> • obtain input from standard input stream and direct it to a variable (extract from stream to variable) inserterinserter operatoroperator <<<< • insert data into standard output stream EGGEGG ILLILL • Extractor Greater Greater, Inserter Less Less

Mr. Dave Clausen 32 InputInput

•• DataData readread inin fromfrom keyboardkeyboard mustmust matchmatch thethe typetype ofof variablevariable usedused toto storestore datadata •• InteractiveInteractive InputInput enterenter valuesvalues fromfrom keyboardkeyboard whilewhile thethe programprogram isis runningrunning cincin causescauses thethe programprogram toto stopstop andand waitwait forfor thethe useruser toto enterenter datadata fromfrom thethe keyboardkeyboard promptprompt thethe useruser forfor thethe datadata (user(user friendly)friendly)

Mr. Dave Clausen 33 Input:Input: SampleSample ProgramsPrograms

NoNo promptprompt forfor anyany ofof thethe datadata values:values:

input.cppinput.cpp input.txtinput.txt

OneOne promptprompt forfor eacheach datadata valuevalue (preferred)(preferred)

triples.cpptriples.cpp triples.txttriples.txt

Mr. Dave Clausen 34