| Math Operation | C++ Operator |
| Add | + |
| Subtract | - |
| Multiply | * |
| Divide | / |
| Mod | % |
For integers A and B,
A % B returns the remainder when A is divided by B.
A/B returns the quotient when A is divided by B.
Examples:
20/3 = 6
20%3 = 2
20%20 = 0
Note that if one of the operands is floating point the value of the
expression is floating point.
20.0/3 = 6.666667
20/3.0 = 6.666667
Order of Precedence of Operations:
1. All operators within parentheses
2. If there are nested parentheses innermost are performed first
3. *, /, % are performed from left to right
4. +, - are performed from left to right
Example:
5/4*9 + 10%7 = 1*9 + 3 = 12.
Problem: Compute average of integer variable objects A, B, C, D
and assign to integer variable Average.
Average = (A + B + C + D)/4;
Suppose that A, B, C, D have values 3, 3, 3, 2, respectively, Then,
Average is assigned the value (3 + 3 + 3 + 2)/4 = 11/4 = 2.
What if we wish to round to the nearest integer. Answer:
Average = (A + B + C + D)/4.0 + .5;
Computer first computes:
(A + B + C + D)/4.0 + .5 = 2.75 + .5 = 3.25
Then 3.25 is assigned to Average. But because Average is an integer
object variable, it is assigned the value 3.
Increment and Decrement Operators
y = ++x; same as x = x + 1; y = x; //PREINCREMENT
y = --x; same as x = x - 1; y = x; //PREINCREMENT
y = x++; same as y = x; x = x + 1; //POSTINCREMENT
y = x--; same as y = x; x = x - 1; //POSTINCREMENT
Avoid ambiguous expressions such as
3*X+++Y
Use parentheses, i.e.
(3*X++)+ Y
Assignment Operators
A = B; assigns value of B to A
A += B; same as A = A+B;
A -= B; same as A = A-B;
A *= B; same as A = A*B;
A /= B; same as A = A/B;
A %= B; same as A = A%B;
Boolean Relational Operators
| Boolean Operation | C++ Operator |
| equal | == |
| not equal | != |
| less than | < |
| less than or equal | <= |
| greater than | > |
| greater than or equal | >= |
In C++ false has value 0 and true has value 1.
Example:
7 == 7 has value 1 (true)
BE CAREFUL:
7 = 7 has value 7 (since = is the assignment operator!)
Other examples:
'A' < 'Y' has the value 1 (true)
'a' < 'B' has the value 0 (false)
7 != 6 has the value 1 (true)
7 >= 13 has the value 0 (false)
Logical Operators
| Logical Operation | C++ Operator |
| NOT | ! |
| OR | || |
| AND | && |
Truth Tables
| NOT (!) | T | F |
| F | T |
| OR (||) | T | F |
| T | T | T |
| F | T | F |
| AND (&&) | T | F |
| T | T | F |
| F | F | F |
Examples:
(5<7)&&(8==6) has value 0 (false)
(5<7)&&(8!=6) has value 1 (true)
(5<7)||(8==6) has value 1 (true)