Arithmetic Operators

Operation Symbol
addition +
subtraction -
multiplication *
division /
modulus (remainder) %

Division

There are two types of division: integer and floating point. Floating point division yields a floating point result. Integer division results in an integer result. Since the integer result cannot contain a fractional part, and fractional part of the result is truncated. For example:

Operation Type Result
15.0 / 2.0 floating point 7.5
15 / 2 integer 7
19.0 / 5.0 floating point 3.8
19 / 5 integer 3

Modulus

The modulus operator, often called mod, returns the remainder of an integer division. For example:

Operation Result
15 % 2 1
19 % 5 4
5 % 8 5 (5 / 8 is 0 with remainder 5)
5 % 0 undefined (division by 0)

Operator Precedence

When a statement has more than one operator we need rules to determine which operator is executed first. Multiplication and division (including mod) have higher precedence than addition and subtraction. The highest precedence is assigned to the minus sign (called unary minus or unary negation, because it only has one operand).

Operator(s) Precedence
- (unary minus) 1 (highest)
* / % 2
+ - 3 (lowest)

If an expression contains multiple operators of the same precedence, then the associativity of the operators determines the order in which they are executed. Associativity is either right-to-left or left-to-right. For example, in the expression 15 * 2 / 5, associativity determines which to execute first: the multiplication or the division.

Operator(s) Associativity
- (unary minus) right to left
* / % left to right
+ - left to right

Parentheses can be used to override the default order of operations.

Examples

Expression Value
10 - 3 * 4 -2
12 / 2 - 1 5
5 + 3 * 6 - 1 22
7 - 20 % 3 + 4 9
4 - 5 * 2 + 11 / 3 - 6 + 1 -9
(10 - 3) * 4 28
12 / (2 - 6) -3
5 + 3 * (6 - 1) 20
(7 - 20) % 3 + 4 3
(4 - 5) * (2 + 11) / 3 - 6 + 1 -9

Email Me | Office Hours | My Home Page | Department Home | MCC Home Page

© Copyright Emmi Schatz 2013