ptg7068951
Using Expressions 59
Comparisons are discussed during Hour 7. The rest has been described
during this hour, so you should be able to figure out the result of the fol-
lowing statements:
int x = 5;
int number = x++ 6 + 4 10 / 2;
These statements set the numbervariable equal to 50.
How does the computer come up with this total? First, the increment oper-
ator is handled, and x++sets the value of the xvariable to 6. However,
make note that the ++operator is postfixed after xin the expression. This
means that the expression is evaluated with the original value of x.
Because the original value of xis used before the variable is incremented,
the expression becomes the following:
int number = 5 6 + 4 10 / 2;
Now, multiplicationand divisionare handled from left to right. First, 5 is
multiplied by 6, 4 is multiplied by 10, and that result is divided by 2 (4 *
10 / 2). The expression becomes the following:
int number = 30 + 20;
This expression results in the numbervariable being set to 50.
If you want an expression to be evaluated in a different order, you can use
parentheses to group parts of an expression that should be handled first.
For example, the expression x = 5 * 3 + 2;would normally cause xto
equal 17 because multiplication is handled before addition. However, look
at a modified form of that expression:
x = 5 * (3 + 2);
In this case, the expression within the parentheses is handled first, so the
result equals 25. You can use parentheses as often as needed in a statement.
Using Expressions
When you were in school, as you worked on a particularly unpleasant
math problem, did you ever complain to a higher power, protesting that
you would never use this knowledge in your life? Sorry to break this to
you, but your teachers were right—your math skills come in handy in your
computer programming. That’s the bad news.