6. Number Operators

As you have already seen in some of the examples above, basic math operations are present in C++. These include + (addition), - (subtraction), * (multiplication), and / (division).  Another important operation is the modulus operator. Modulus is represented by the “%” symbol, and gives the remainder of a mathematical operation between integers. For example, 22%10 would return 2, and 35%8 would return 3

A list of these is given in this table:

More mathematical operations can be used by including the “cmath” library at the beginning of your code, which allows for the use of exponents (with ^) and trigonometric functions (sin, cos, etc.). 

A significant part of coding deals with comparing objects. When comparing two objects, a boolean value is returned (true or false, 1 or 0). This is done by using symbols you are already familiar with in mathematics. Here is a table containing the comparison operators we will be using: 

Keep in mind that the operator for determining if two things are equivalent is different than what you use to assign variables! When assigning a variable a value you use a single = (e.g.  a = 4;), but when you are comparing two values you must use double ==, and an error will occur if you don’t. 

Here are some quick examples of the boolean values returned in a variety of cases in this table:

These will be very important in your first activity. The other part of these comparisons is the use of “and”, “or”, and “not”. These are known as logical operators. “And” is represented by the symbols “&&”, “or” is represented by “||”, and “not” by “!”. The “not” operator is simple - it gives the inverted boolean value of its input. So, if the input is true, it outputs false, and if the input is false, it outputs true. The “and” and “or” operators are slightly more complicated, and both take two inputs. For “and”, both values must be true for the output to be true, otherwise false is returned. For “or”, only one value must be true to output true. A table of all possible outputs of these two operators are given below: 

An important note is that these operators can only be used on variables of the same type. For example, even though an int and double may both be numbers, they cannot be compared using any of the operators.