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:
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.