**Unary arithmetic operators**

There are two unary arithmetic operators, plus (+), and minus (-). If you remember, unary operators are operators that only take one operand.

Operator | Symbol | Form | Operation |
---|---|---|---|

Unary plus | + | +x | Value of x |

Unary minus | - | -x | Negation of x |

The unary plus operator returns the value of the operand. In other words, +5 = 5, and +x = x. Generally you won’t need to use this operator since it’s redundant. It was added largely to provide symmetry with the unary minus operator.

The unary minus operator returns the operand multiplied by -1. In other words, if x = 5, -x = -5.

For best effect, both of these operators should be placed immediately preceding the operand (eg. `-x`

, not `- x`

).

Do not confuse the unary minus operator with the binary subtraction operator, which uses the same symbol. For example, in the expression `x = 5 - -3;`

, the first minus is the subtraction operator, and the second is the unary minus operator.

**Binary arithmetic operators**

There are 5 binary arithmetic operators. Binary operators are operators that take a left and right operand.

Operator | Symbol | Form | Operation |
---|---|---|---|

Addition | + | x + y | x plus y |

Subtraction | - | x - y | x minus y |

Multiplication | * | x * y | x multiplied by y |

Division | / | x / y | x divided by y |

Modulus (Remainder) | % | x % y | The remainder of x divided by y |

The addition, subtraction, and multiplication operators work just like they do in real life, with no caveats.

Division and modulus (remainder) need some additional explanation.

**Integer and floating point division**

It is easiest to think of the division operator as having two different “modes”. If both of the operands are integers, the division operator performs integer division. Integer division drops any fractions and returns an integer value. For example, 7 / 4 = 1 because the fraction is dropped. Note that integer division does not round.

If either or both of the operands are floating point values, the division operator performs floating point division. Floating point division returns a floating point value, and the fraction is kept. For example, 7.0 / 3 = 2.333, 7 / 3.0 = 2.333, and 7.0 / 3.0 = 2.333.

Note that trying to divide by 0 (or 0.0) will generally cause your program to crash, as the results are undefined!

**Using static_cast<> to do floating point division with integers**

In section 2.7 -- Chars, we showed how we could use the static_cast<> operator to cast a char to an integer so it would print correctly.

We can similarly use static_cast<> to convert an integer to a floating point number so that we can do floating point division instead of integer division. Consider the following code:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
#include <iostream> int main() { int x = 7; int y = 4; std::cout << "int / int = " << x / y << "\n"; std::cout << "double / int = " << static_cast<double>(x) / y << "\n"; std::cout << "int / double = " << x / static_cast<double>(y) << "\n"; std::cout << "double / double = " << static_cast<double>(x) / static_cast<double>(y) << "\n"; return 0; } |

This produces the result:

int / int = 1 double / int = 1.75 int / double = 1.75 double / double = 1.75

**Modulus (remainder)**

The modulus operator is also informally known as the remainder operator. The modulus operator only works on integer operands, and it returns the remainder after doing integer division. For example, 7 / 4 = 1 remainder 3, thus 7 % 4 = 3. As another example, 25 / 7 = 3 remainder 4, thus 25 % 7 = 4.

Modulus is very useful for testing whether a number is evenly divisible by another number: if x % y == 0, then we know that y divides evenly into x.

For example, say we wanted to write a program that printed every number from 1 to 100 with 20 numbers per line. We could use the modulus operator to determine where to do the line breaks. Even though you haven’t seen a while statement yet, the following program should be pretty comprehensible:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
#include <iostream> int main() { // count holds the current number to print int count = 1; // start at 1 // Loop continually until we pass number 100 while (count <= 100) { std::cout << count << " "; // print the current number // if count is evenly divisible by 20, print a new line if (count % 20 == 0) std::cout << "\n"; count = count + 1; // go to next number } // end of while return 0; } // end of main() |

This results in:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100

We’ll discuss while statements in a future lesson.

**A warning about integer division and modulus with negative numbers prior to C++11**

Prior to C++11, if either of the operands of integer division are negative, the compiler is free to round up or down! For example, -5 / 2 can evaluate to either -3 or -2, depending on which way the compiler rounds. However, most modern compilers truncate towards 0 (so -5 / 2 would equal -2). The C++11 specification changed this to explicitly define that integer division should always truncate towards 0 (or put more simply, the fractional component is dropped).

Also prior to C++11, if either operand of the modulus operator is negative, the results of the modulus can be either negative or positive! For example, -5 % 2 can evaluate to either 1 or -1. The C++11 specification tightens this up so that `a % b`

always resolves to the sign of `a`

.

**Arithmetic assignment operators**

Operator | Symbol | Form | Operation |
---|---|---|---|

Assignment | = | x = y | Assign value y to x |

Addition assignment | += | x += y | Add y to x |

Subtraction assignment | -= | x -= y | Subtract y from x |

Multiplication assignment | *= | x *= y | Multiply x by y |

Division assignment | /= | x /= y | Divide x by y |

Modulus assignment | %= | x %= y | Put the remainder of x / y in x |

Up to this point, when you’ve needed to add 5 to a variable, you’ve likely done the following:

1 |
x = x + 5; |

This works, but it’s a little clunky, and takes two operators to execute.

Because writing statements such as x = x + 5 is so common, C++ provides 5 arithmetic assignment operators for convenience. Instead of writing x = x + 5, you can write x += 5. Instead of x = x * y, you can write x *= y.

**Where’s the exponent operator?**

You’ll note that the ^ operator (commonly used to denote exponentiation in standard mathematical nomenclature) is a Bitwise XOR operation in C++. C++ does not include an exponent operator. To do exponents in C++, #include the <cmath> header, and use the pow() function:

1 2 3 |
#include <cmath> double x = std::pow(3.0, 4.0); // 3 to the 4th power |

Note that the parameters (and return value) of pow in the above example are of type double. std::pow() assumes the base is a floating point number. Note that due to rounding errors in floating point numbers, the results of pow() may not be precise (slightly smaller or larger than what you’d expect).

If you want to do integer base, you’re best off just using your own function to do so, like this one (that uses the non-intuitive “exponentiation by squaring” algorithm for efficiency):

1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
// note: exp must be non-negative int pow(int base, int exp) { int result = 1; while (exp) { if (exp & 1) result *= base; exp >>= 1; base *= base; } return result; } |

Don’t worry if you don’t understand all of the parts of this function yet. Just beware of overflowing your integer result, which can happen very quickly if either argument is large.

**Quiz**

1) What does the following expression evaluate to? `6 + 5 * 4 % 3`

2) Write a program that asks the user to input an integer, and tells the user whether the number is even or odd. Write a function called isEven() that returns true if an integer passed to it is even. Use the modulus operator to test whether the integer parameter is even.

Hint: You’ll need to use if statements and the comparison operator (==) for this program. See lesson 2.6 -- Boolean values and an introduction to if statements if you need a refresher on how to do this.

**Answers**

3.3 -- Increment/decrement operators, and side effects |

Index |

3.1 -- Operator precedence and associativity |

So I gave myself a challenge to write a geometric sequence and then display the last number in the sequence and state whether it's even or odd.

1. Is there any way I can improve this

2. I'm beginning to understand while loops. How do I do this:

if the user inputs a decimal number for "Enter a power: ". It'll output an speech and loop them back to question "Enter a power: " again until they give an integer without decimal point.

Hi Rai!

1.

* Initialize your variables with uniform initialization

* Line 32: You can use single quotation marks to make your numbers more readable (1'000'000)

* Line 32: This loop could be infinite if @power <= 1

* Use double numbers when calculating with doubles (1.0 instead of 1 etc.)

2.

Thanks. One thing. You told me about Initialize your variables with uniform initialization before but I don't understand what this means - how to use {} to initialize variables. Could you show an example.

This is part of lesson 2.1. Unfortunately, Alex doesn't use uniform initialization himself in most of the lessons.