CS 150 Introduction to C++ Programming - Spring 1998 

[ Home | Lecture Notes| WebTutor | WebTutor Site Map]


Evaluating Arithmetic Expressions (Exercise 2 Chapter 3)


Arithmetic expressions can be ambiguous if there is more than one way to perform the calculation. For instance, what is the value of the expression

		5+4*3

Is it 17(5 + 12) or is it 27(9*3)? To solve this problem, arithmetic expressions are evaluated according to certain rules such as precedence and grouping order. Precedence refers to the priority given to different arithmetic operators (i.e. which ones will be done first).
For C++, the precedence of operators is

Parenthesis ()
Multiplicative Group * / %
Additive Group + -

For more details see page 94, or A1-2 in the text
For operators of the same precedence, the order of evaluation is left to right.

What value is stored in the "int" variable "result" in each of the following? (from exercise 2 page 125)

  1. result = 14 % 4;

  2. result = 7 / 3 + 5;

  3. result = 2 + 7 * 5;

  4. result = 42 / 8 * 4 + 2;

  5. result = 17 + (21 - 6) * 2;

  6. result = int(4.5 + 2.6 * 0.5);

 

Choose one when done
   

Copyright chris wild 1998.
For problems or questions regarding this web contact [Dr. Wild (e-mail:wild@cs.odu.edu].
Last updated: February 08, 1998.