3D. Expressions

You should be familiar with expressions from algebra. You evaluate an expression, and the evaluation yields a value. For example, evaluating expression 2 + 5 yields value 7.

C++ and Java support the same arithmetic operators, including

See more detail on elementary C++ expressions.

Watch out. Division of integers always produces an integer result. Everything after the decimal point is thrown away. The value of C++ expression 5/3 is 1.


Precedence

Binary operators *, / and % have higher precedence than + and -. For example, expression 1 + 2 * 3 has value 7, since the multiplication is done first. Use parentheses to force the order of evaluation. Expression (1 + 2) * 3 has value 9.

Binary operators listed above that have the same precedence are done from left to right. So expression 5 - 2 - 1 has value 2.

See more detail on operator precedence and order of evaluation.


Exercises

  1. What is the value of C++ expression 5-1-1? Answer

  2. What is the value of expression 5/4? Answer

  3. What is the value of expression 9/5? Answer

  4. What is the value of expression 9%5? Answer

  5. What is the value of expression 12/2*2? Answer