In the last lesson we saw that our rule for the assignment operation included variables, constants, and something called expressions. Expressions are mathematical combinations of numbers, variables, and constants. Usually the result of an expression is stored in another variable. You can think of expressions as being very similar to equations in mathematics. A typical equation might look like this:

 Assignment Operation Expression
 yCoordinate := SLOPE * xCoordinate + 4

You may remember from algebra class that this is the equation for a line. Notice that all the parts of the equation are either variables, constants, numbers, or mathematical operators. The right side of the equation is an expression and the left side of the equation is an assignment operation that stores the result of the expression in the variable yCoordinate. By combining many different variables, constants, and numbers, we can build complex expressions for solving mathematical problems with computer programs.

What happens when we try to construct a longer expression like the following one:

 result := 6 + 10 / 2 - 4 * 2

How do we know which operations in the expression to calculate first? The answer to this question is solved by the rules of operator precedence in a programming language. These rules define which operations must be performed first. In mathematics, the multiplication and division operations are performed first and then addition and subtraction are performed. Using this rule, the value stored in result would be 3.

 result := 6 + 10 / 2 - 4 * 2 result := 6 + 5 - 8 result := 11 - 8 result := 3

However, we can change the order of operations by enclosing a part of the expression in parentheses like this:

 result := (6 + 10) / 2 - 4 * 2

The parentheses tell us to compute the value of (6 + 10) before we perform the division by 2. With this change, the value stored in result is now 0. By using parentheses we can override the normal order of operations in our expressions.

 result := (6 + 10) / 2 - 4 * 2 result := 16 / 2 - 8 result := 8 - 8 result := 0

Do not forget that expressions can also contain variables and constants as well as numbers. Some example expressions and assignment operations are listed in the table below.

 Assignment Operation Expression
 average := (10 + 9 + 6 + 11) / 4
 averagePrice := numberOfBoxes / BOXPRICE
 totalStudents := class1 + class2 + class3