Arithmetical Operators:

• Arithmetical operators of C:

 +     add -     subtract *     multiply /     divide %     take remainder of an integer division

Remember that:

 Arithmetic operators in computer programs must always operate on two values of the same data type !!! The result of the arithmetic operation will always have the same data type as the operands.

• I am skipping the remainder of this webpage !!!

• Because:

• Arithmetic operators in C behave the same way as arithmetic operators in Java

• You can refresh the properties of

 Automatic onversion Priority of operators Associativity of operators

by reading the remainder of this webpage if necessary.

• Arithmetical operators with values of different type

• When values of different types are used in an arithmetic operation, the value of the narrow type is AUTOMATICALLY converted to the wider type

• Then the operation is performed on the two value of same type

• Examples:

 ``` 2.0 + 3 --> 2.0 + 3.0 = 5.0 (result is double) (int) 2 + (short) 3 --> (int) 2 + (int) 3 = (int) 5 ```

• WARNING: Integer Division in C/C++:

• Pay special attention on the division / operator:

• floating point division computes quotient and the remainder in decimal places

• integer division computes the integral quotient.

Examples:

 ``` 7.0 / 4.0 = 1.75 (divide 2 double values, natural) 7 / 4.0 = 1.75 (7 / 4.0 --> 7.0 / 4.0 = 1.75) 7.0 / 4 = 1.75 (7.0 / 4 --> 7.0 / 4.0 = 1.75) 7 / 4 = 1 <- integer division ! ```

Operator Priority & Associativity

• How is an expression in programs evaluated ?

• Arithmetic expression in programming languages are evaluated according to strict rules of priority.

• Each operator in a programming language is assigned:

• a priority level

• an associativity direction

• The following 2 rules are used in evaluating expressions:

• Operations involving operators of higher priority are evaluated before lower priority operators.

• When operators have the same priority, then the expression is evaluated in the direction given by their associativity direction

• Priority and Associativity of Arithmetic operators in C/C++

• Warning: different programming languages may have different priority and associativity rules !

• Priority & Associativity of Arithmetic Operators in C/C++:

Priority Operator(s) Associativity
1   *   /   % left -> right
2   +   - left -> right

• Some examples:

 ``` 6 - 2 * 5 ``` ``` -> 6 - (2 * 5) -> (6 - 10) -> -4 ``` ``` 6 - 2 * 5 - 8 / 3 ``` ``` -> 6 - (2 * 5) - (8 / 3) -> 6 - 10 - 2 [Same priority: use assoc rule !] -> (6 - 10) - 2 -> -4 - 2 -> -6 ``` ``` 6.0 - 8 / 5 ``` ``` -> 6.0 - 8 / 5 -> 6.0 * 1 [double + int: convert !] -> 6.0 * 1.0 -> 6.0 ``` ``` 6.0 * 8 / 5 ``` ``` -> 6.0 * 8.0 / 5 -> 48.0 / 5 [double / int: convert!] -> 48.0 / 5.0 -> 9.6 ```