Data
Basic skills
Order of preference
The order of precedence for arithmetic operations
- Increment and decrement
- Positive and negative
- Multiplication, division, and remainder
- Addition and subtraction
How to work with the order of precedence
- Unless parentheses are used, the operations in an expression take place from left to right in the order of precedence.
- To specify the sequence of operations, you can use parentheses.
- When you use an increment or decrement operator as a prefix to a variable, the variable is incremented or decremented and then the result is assigned.
- When you use an increment or decrement operator as a postfix to a variable, the result is assigned and then the variable is incremented or decremented.
Example 1: A calculation that uses the default order of precedence
double discountPercent = .2; // 20% discountdouble price = 100; // $100 price
price = price * 1 - discountPercent; // price = $99.8
The same calculation with parentheses that specify the order of precedence
price = price * (1 - discountPercent); // price = $80Example 2: An investment calculation based on a monthly investment and yearly interest rate
double currentValue = 5000; // current value of investment accountdouble monthlyInvestment = 100; // amount added each month
double interestRate = .12; // yearly interest rate
currentValue = (currentValue + monthlyInvestment) * (1 + (interestRate/12)); // currentValue = 5100 * 1.01 = 5151
Another way to calculate the current value of the investment account
currentValue += monthlyInvestment; // add investment// calculate interest
double monthlyInterest = currentValue * interestRate / 12;
currentValue += monthlyInterest; // add interest
Example 3: Prefixed and postfixed increment and decrement operators
int a = 5;int b = 5;
int y = ++a; // a = 6, y = 6
int z = b++; // b = 6, z = 5