Defined on values of various types. You can apply an operator to a variable, but that just means to use its value.
+ - * / %
/ gives "floor": 9/4 = 2 % gives "remainder": 9%4 = 1
+ - * /
/ is floating divide: 9.0/4.0 = 2.25
What is 7 + 4 * 3?
(7 + 4) * 3 = 33? or 7 + (4 * 3) = 19?
Answer: * has higher precedence, so the correct equation is 7 + (4 * 3). The book gives detailed precedence rules on page 771, but when in doubt put parens in. Do it when there is any question so that you and the reader of the program will be sure.
++, -- before and after. See increment.cpp Demo
Not all programs are just a straight shot through lines of code. Sometimes we need new structures to facilitate our needs. We want to be able to loop and to execute one of several alternatives. To do this we need conditions.
All decisions about executing loops and alternatives are based on conditions. Strictly speaking, a condition is just an integer-valued expression. If the expression is equal to 0, then it is considered false. If the expression is not equal to 0 then it is considered to be true.
The following relational operators evaluate to 0 or 1.
C++ also contains the following logical connective operators:
Example
int a = 9, b = 4, c; c = (b != 0 && a/b > 1); cout << c; //prints 1But if b == 0, c is 0, and a/b is not evaluated because of the "short-circuiting mechanism".
Pitfall Example
int a = 5, b = 4, c = 3, d; d = A > b > c; cout << d; /prints 0This occurs because a > b > c is really: (a > b) > c --> (5 > 4) > 3 --> 1 > 3 --> 0. To correct this, use (a > b) && (b > c)
if (expression) or if(expresson) stmt; stmt; else stmt; Examples if (goals >= 10){ if(year % 4 == 0) Yell(); cout << "Election year"; BreakStick(); else } cout << "We're safe"; GoHome();
Note
What the computer will do is test the expression. If it does not equal to 0 then it will do the body. Eventually the expression will equal 0 and the next statement after the body is executed. There had better be a way to make the expression be zero in the loop. Otherwise you will have created an infinite loop!!while (expression) <--- header stmt; <--- body
Notes:
{ stmt; stmt; . . . }
See electionyear.cpp and infloop.cpp Demos
To Index Previous Next