An associative operation may refer to any of the following:
- In mathematics, an associative operation is a calculation that gives the same result regardless of the way the numbers are grouped. Addition and multiplication are both associative, while subtraction and division are not. For example, take a look at the calculations below.
Associative
2+(2+5) = 9 (2+2)+5 = 9
Not associative
4-(2-1) = 3 (4-2)-1 = 1
In the additional examples, it does not matter the order the numbers are added. Whether adding 2+5 first and then adding 2, or adding 2+2 first and then adding 5, the result is 9 and makes it associative. On the other hand, subtraction is not associative since changing the grouping changes the result.
- In programming, an associative operation occurs when no grouping is present, where operators have the same precedence, or are evaluated either left to right or vice versa. If neither of these is the case in the programming language, then it’s either a special operator or gives a syntax error.
For example, addition and subtraction have the same precedence and are left-associative. Thus, if there is no grouping with parentheses, the operators are evaluated from left to right. For example, 4-3+1 equals 2, since 4-3 is calculated first, with the result being added to 1. To change this order, the programmer needs to group the numbers to calculate the expression as desired. If the programmer wants to perform the 3+1 calculation first, it can be grouped using parentheses, as shown below.
4-(3+1)
This forces 3+1 to be calculated first, with the result (4) subtracted from 4, giving zero.
With most languages, addition, subtraction, multiplication, and division operators are left-associative, while the assignment, conditional, and exponentiation operators are right associative.
Operator, Programming terms
Related pages
- How to create a computer program.