
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 <iostream.h><iostream.h> ////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 <iostream.h><iostream.h> ////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++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,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 <iostream.h> 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 division, 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 <iostream.h> 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 <iostream.h> 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 <iostream.h> 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.
Details
-
File Typepdf
-
Upload Time-
-
Content LanguagesEnglish
-
Upload UserAnonymous/Not logged-in
-
File Pages34 Page
-
File Size-