5. Calculations
Our programs frequently need to perform one or more calculations. In C++ we have a number of operators available with which to perform arithmetic.
Assignment Statements
Before we can take a look at our options for performing a calculation, we need to understand how to save the result as most of the time it will be needed for a later step in the program. In C++, an assignment statement is used to save the result of a calculation:
variable = expression;
The variable is where the result of the calculation will be stored for later use. The equal sign, called an assignment operator in C++, is used to assign the result to the variable. An expression can take a variety of forms, but always results in a value to be assigned to the variable. Assignment statements always end with a semicolon. Here are examples of assignment statements and expressions (assume all of the variables have already been declared):
number = 4; // assigns 4 to the variable 'number'
amount = number; // assigns the value of the variable
// 'number' (4) to the variable 'amount'
sum = 1 + 2; // assigns 3 to the variable 'sum'
// (1 + 2 is 3)
answer = sum – 5; // assigns -2 to the variable 'answer'
// (3 - 5 is -2)
total = answer + amount; // assigns 2 to the variable 'total'
// (-2 + 4 is 2).
As can be seen, an expression can be a single number, the value of a single variable, or the result of a calculation involving numbers and/or variables.
The variable to assign the result to must always be on the left of the assignment operator. Assignment statements always assign the value on the right to the variable on the left. If the value is instead placed on the left, the program will not compile:
7 = variable; // Wrong!
Arithmetic Operators
In mathematics, the four basic arithmetic operations are addition, subtraction, multiplication, and division. In C++ we have operators for each as well as one additional type of operation.
Addition, Subtraction, and Multiplication Operators
The operators for addition and subtraction in C++ are the same as they are in math: ‘+’ for addition and ‘–’ for subtraction. For multiplication an asterisk (‘*’) is used. The operators work as we would expect (assume the variables have already been declared):
sum = 2 + 7; // assigns 9 to 'sum'
difference = 8.25 – 5.5; // assigns 2.75 to 'difference'
product = 4 * 6; // assigns 24 to 'product'
Multiplication cannot be assumed. For example, in math 3y is understood to be 3 times the value of the variable y. In C++, the * must be present or the program will not compile. Instead of 3y, the calculation must be written 3 * y.
Division Operator
There are two types of division in C++: integer and floating-point. The type of division performed is determined by the data types of the operands used with the division operator (‘/’). If one or both operands are floating-point values, floating-point division is performed and the result is the correct mathematical result. If both operands are integers, integer division is performed and the result is an integer. Here are examples of both types of division and further explanation:
| Math | Floating-Point Division | Integer Division | Explanation |
|---|---|---|---|
| 7 / 4 is 1.75 | 7.0 / 4 7 / 4. 7. / 4.0 are all 1.75 | 7 / 4 is 1 | The mathematical result is 1.75, which is also the result when one or both operands is a floating-point value and floating-point division is performed. When both operands are integers, the result is an integer. The .75 in the mathematical result is therefore truncated and the result of the division is 1. |
| 5 / 8 is 0.625 | 5 / 8. 5.0 / 8 5.0 / 8.0 are all 0.625 | 5 / 8 is 0 | The mathematical result of 0.625 is obtained in the floating-point division examples because at least one operand is a floating-point value. The result when 5 is divided by 8 is 0 because both 5 and 8 are integers and therefore the fractional part of the mathematical answer, .625, is truncated. |
As can be seen, only a decimal point is needed to make a number a floating-point value. Nothing needs to appear after the decimal point. Also note that rounding does not occur with integer division. The fractional part of the number is just dropped off (truncated in programming). Keep in mind that the operands could also be variables.
As in mathematics, division by zero cannot be performed in a program. If attempted, the program will either fail to compile or run unsuccessfully.
Remainder/Modulus Operator
The one additional mathematical operation we have in C++ involves the use of the remainder (aka modulus) operator. When used, division is performed but the result is the remainder. The operator itself is a percent sign (‘%’) and both operands must be integers. If either operand is not an integer, the program will not compile. Here are some examples of the operator’s use:
result = 12 % 4; // 4 divides evenly into 12 with nothing
// left over. Value assigned: 0.
result = 25 % 5; // 5 divides evenly into 25 with nothing
// left over. Value assigned: 0.
result = 17 % 6; // 6 goes into 17 two times with 5 left over.
// Value assigned: 5.
result = 11 % 3; // 3 goes into 11 three times with 2 left over.
// Value assigned: 2.
result = 3 % 5; // 5 does not go into 3. Value assigned is the
// number divided into: 3.
result = 0 % 14; // 14 does not go into 0. Value assigned is the
// number divided into: 0.
When expressions using the remainder operator are read out loud, “mod” (short for modulus) is sometimes used. For example, 12 % 4 can be read “12 mod 4”.
Since division by zero cannot be performed by our programs, the remainder operator cannot be used to find the remainder when a number is divided by zero (e.g., 8 % 0). If attempted, a program will either fail to compile or run unsuccessfully.
Operator Precedence and Associativity
So far, our calculations have involved only a single operator other than the assignment operator. Often, however, programs need to perform calculations in which multiple operators are used (e.g., ‘+’ and ‘*’). How is the order in which the operators are used determined?
Operator Precedence
Every operator is assigned a precedence level to assist in determining when it will be acted upon if placed in an expression with multiple operators. The multiplication (‘*’), division (‘/’), and remainder (‘%’) operators all have the same precedence level. The addition (‘+’) and subtraction (‘-’) operators have the same precedence level but one which is lower than that of the other three operators. As a result, addition and subtraction will be performed after the other three operations:
result = 5 – 8 * 3; // Order: multiplication, then subtraction;
// 'result' is -19
result = 12 / 7 – 4; // Order: division, then subtraction;
// 'result' is -3 (12 and 7 are integers)
result = 9 + 16 % 2 // Order: remainder, then addition;
// 'result' is 9 (2 divides 16 evenly)
The concept of assigning operators an order in which they will be evaluated is called, in programming, operator precedence (in math it is called “order of operations”).
Operator Associativity
What happens when there are multiple operators with the same precedence level in the same expression (e.g., 3 + 7 * 5 / 2 - 8)? Operator precedence states multiplication and division should both be performed first, but only one operator can be acted on at a time. So operator precedence does not provide a complete answer. Operator associativity fills the gap.
If multiple operators with the same precedence level are used in an expression, they will be evaluated left to right, or right to left, depending upon the associativity of the operators. The arithmetic operators have left to right associativity, so they will be evaluated left to right. The order in which the operators in the preceding calculation will be evaluated is shown below. The sole impact of operator precedence is shown first, then the impact of both operator precedence and associativity is demonstrated:
// Operator precedence only
// (2) (1) (1) (2)
result = 3 + 7 * 5 / 2 – 8;
// Operator precedence and associativity ('result' is 12)
// (3) (1) (2) (4)
result = 3 + 7 * 5 / 2 – 8;
Operator precedence determines that multiplication and division will be performed prior to addition and subtraction. Operator associativity says multiplication will be performed before division in the example above because the multiplication operator is to the left of the division operator. Addition will be performed before subtraction for the same reason. Putting everything together, the operators will be evaluated in the order multiplication, division, addition, and then subtraction.
Two additional examples:
// Operator precedence and associativity ('result' is 6)
// (1) (3) (2)
result = 6 % 11 + 4 / 9
// Operator precedence and associativity ('result' is 9)
// (3) (4) (1) (2)
result = 15 - 10 + 4 * 8 % 7
In case you’re curious, one operator with right to left associativity is the assignment operator. Here is a circumstance in which this associativity would be utilized:
// Operator associativity
// (3) (2) (1)
num1 = num2 = num3 = 5;
When the statement is executed, 5 would be assigned to num3, the value of num3 then assigned to num2, and finally the value of num2 assigned to num1. So the assignment operators are acted upon from the right to the left and all three variables would, in the end, have a value of 5. Keep in mind that the variables have previously been declared. This approach cannot be taken to initialize variables at the time they are declared (the program will not compile).
Parentheses can be used to counter the order in which operators are normally evaluated. As in math, operations placed in parentheses will be evaluated first:
// Operator precedence and associativity ('result' is -39)
// (4) (3) (1) (2)
result = 3 + 7 * (5 / 2 - 8);
// Operator precedence and associativity ('result' is 15)
// (4) (1) (2) (3)
result = 15 - (10 + 4) * 8 % 7;
Compound Assignment Operators
C++ has a number of operators which exist solely for writing expressions in an alternative, abbreviated format. None of these operators provide any new capabilities. The compound assignments operators (+=, -=, *=, /=, and %=) are one such case. Examples of their use are as follows (assume the variables used are already declared and have values):
| Original Version | Rewritten Version | Explanation |
|---|---|---|
number = number + 4; | number += 4; | Add value of number to 4 and store result in number. |
amount = amount – 8; | amount -= 8; | Subtract 8 from value of amount and store result in amount. |
answer = answer * 2; | answer *= 2; | Multiply value of answer by 2 and store result in answer. |
total = total / 7; | total /= 7; | Divide value of total by 7 and store result in total. |
quantity = quantity % 9; | quantity %= 9; | Divide value of quantity by 9 and store remainder in quantity. |
In each case, the original and rewritten versions of the assignment statements do the exact same thing. No new functionality exists due to the use of the compound assignment operators. Only slightly less code is written.
There is a pattern to the original and revised versions of the assignment statements. The original versions are of the form:
variable = variable op value;
The new versions have the form:
variable op= value;
The word “op” stands for the operator being used. If the patterns are kept in mind as you write your code, opportunities for using these operators may be identified. Also recall that addition and multiplication are commutative: 4+5 is 5+4 and 3*6 is 6*3.
A statement such as:
total = 5 + total;
can be rewritten:
total = total + 5;
and therefore:
total += 5;
The compound assignment operators cannot be reversed. For example, /= cannot be written =/ (with the assignment operator first instead of last). If attempted, the program will not compile.
Increment and Decrement Operators
The increment and decrement operators are also available for writing shorter code. The purpose of these operators is to add 1, or subtract 1, from a variable. The following table summarizes key information about these operators:
| Increment Operator | Decrement Operator |
|---|---|
++ | -- |
| Adds 1 to a variable | Subtracts 1 from a variable |
Preincrement: ++number | Predecrement: --number |
Postincrement: number++ | Postdecrement: number-- |
If the operator is placed before a variable, it is called the preincrement or predecrement operator, as the case may be. When placed after a variable, it is called the postincrement or postdecrement operator.
If a line of code consists solely of adding 1 to, or subtracting one from, a variable (e.g., ++number; or number--;), it does not matter on which side of the variable the operator is placed. In larger expressions, however, the placement of the operator does matter. Here is an increment operator example (assume the variables are declared and the variable number initialized to 3):
| Example | Explanation |
|---|---|
| A preincrement operator is used, so it is acted upon first and Per operator precedence, ( In the final step, |
| A postincrement operator is used, so it is acted upon last. The Per operator precedence, multiplication occurs first ( The variable In the final step, |
As can be seen, using a preincrement operator results in 1 being added to the variable before any other action occurs. When a postincrement operator is used, 1 is not added until all other operators in the assignment statement have been acted upon, even the assignment operator. In both cases, the variable is incremented (number’s value changes from 3 to 4), but the value of the variable which stores the result of the calculation (i.e., answer) is different based upon which version of the operator is used.
When the postincrement operator is used, keep in mind that the final step of adding 1 to the variable has no impact on the result of the calculation (i.e., answer’s value is still -7 after 1 is added to number).
The predecrement and postdecrement operators work equivalently (assume the variables are declared and number is initialized to 5):
| Example | Explanation |
|---|---|
| A predecrement operator is used, so it is acted upon first and Per operator precedence, division occurs next ( In the final step, |
| A postdecrement operator is used, so it is acted upon last. The Per operator precedence, division occurs first ( The variable In the final step, |
Both operators must be used on a variable. If an attempt is made to use either version of either operator on something other than a variable, the program will not compile. For example, these uses of the operators are illegal: ++3 and (j+1)--.