Associative operation

  1. In mathematics, an associative operation is a calculation that will give 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 below calculations.

    Associative:
    2+(2+5) = 9
    (2+2)+5 = 9

    Not Associative:
    4-(2-1) = 3
    (4-2)-1 = 1

    In the addition 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, the subtraction is not associative, since changing the grouping changes the result.
  2. In programming, an associative operation occurs when no grouping is present, where operators that have the same precedence (such as addition and subtraction) will be evaluated either from left to right (left-associative) or from right to left (right-associative). If neither of these is the case within the programming language, then it will either be a special operator or it will give a syntax error, as a result.

    For example, addition and subtraction have the same precedence, and are left-associative. Thus, if there is no grouping with parentheses, the operators will be evaluated from left to right: 4-3+1 will be equal to 2, since 4-3 will be calculated first, with the result being added to 1. To change this order, the programmer would need 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 will force 3+1 to be calculated first, with the result (4) subtracted from 4, giving zero.

    In most programming languages, the addition, subtraction, multiplication, and division operators are left-associative, while the assignment, conditional, and exponentiation operators are right associative.

Also see: Programming definitions