Arithmetic Expressions
Video Summary: https://youtu.be/LflQ33bq2CU
You need to know the definition of an arithmetic expression and the precedence of the operators.
Arithmetic Operators
Variables and constants of integral and floating point types can be combined into expressions using arithmetic operators. The arithmetic operators are listed in the following table:
Operators | Description |
---|---|
+ | Unary plus: needs one operand. |
- | Unary minus: needs one operand. |
+ | Addition: needs two operands. |
- | Subtraction: needs two operands. |
* | Multiplication: needs two operands. |
/ | Division: needs two operands.
|
% | Modulus: needs two operands
|
++ | Increment by one; can be prefix or postfix; as prefix has highest precedence |
-- | Decrement by one; can be prefix or postfix; as prefix has highest precedence |
Precedence of Arithmetic Operations
The precedence rules of arithmetic apply to arithmetic expressions in a program. That is, the order of execution of an expression that contains more than one operation is determined by the precedence rules of arithmetic. These rules state that parentheses have the highest precedence, multiplication, division, and modulus have the next highest precedence, and addition and subtraction have the lowest. The prefix increment and decrement operators have the highest precedence over any of the arithmetic operators.
Look at the following example, and decide what is written by each of the output statements, then click the grey boxes to confirm your answers.
/************************************************************* * * This program demonstrates the precedence of the operators. * *************************************************************/ #include <iostream> using namespace std; int main () { cout << 4 + 3 * 5 << endl; 19 cout << (4 + 3) * 5 << endl; 35 cout << 4 * 5 % 3 + 2 << endl; 4 cout << (4 * (5 % 3) + 2) << endl; 10 return 0; }
You can run the program to verify the results.
Converting Numeric Types
If an integral and a floating point variable or constant are mixed in an operation, the integral value is changed temporarily to its equivalent floating point representation before the operation is executed. This automatic conversion of an integral value to a floating point value is called type coercion. Type coercion also occurs when a floating point value is assigned to an integral variable. Coercion from an integer to a floating point is exact. However, when a floating point value is coerced into an integral value, the fractional part is truncated.
Type changes can be made explicit by placing the value to be changed in parentheses and placing the name of the new type before it. This is called type casting or type conversion. For example:
intValue = 10.66; intValue = int(10.66)
Will both produce the result 10
There are times when you need to do this to get the arithmetic results you want. Consider the results of this sample program: