April 17, 2007
CS211 Prelim 2
Page 1 of 8
1. (20 points) The expression 8

2
*
3 evaluates to 2, since it is understood as 8

(2
*
3),
following the convention that multiplication has precedence over subtraction. If
we wish the operators to be evaluated in a diﬀerent order, say as (8

2)
*
3 = 18,
we must include the parentheses explicitly. Expressions of this form containing
operators such as +
,
*
,

that appear between operands (the values they act upon)
are called
inﬁx
expressions. To evaluate such expressions, you either need to know
the precedence ordering of the operators, or the expression must be parenthesized
to help you interpret which operation to evaluate ﬁrst.
An alternative notation used to represent expressions is
postﬁx notation
. You do
not need to learn any operator precedence rules to evaluate postﬁx expressions.
You also do not need to use parentheses. In any postﬁx expression, all opera
tions appear
after
their corresponding operands, unlike inﬁx, where they appear
between their operands. And unlike inﬁx, the order of evaluation of the operators
is uniquely determined by the postﬁx expression. Due to its unambiguous inter
pretation, postﬁx notation is convenient to use as an intermediate representation
in compilers and calculators.
Some examples:
Inﬁx expression
Postﬁx expression
Value
2 + 3
2 3 +
5
7
*
8
7 8
*
56
6
/
2 + 5
6 2
/
5 +
8
5 + 6
/
2
5 6 2
/
+
8
To evaluate a postﬁx expression, say for example 7 3

5 8 +
*
, you process
the expression from left to right. Whenever you see an operator, you apply it on
the two most recently seen operands, compute the result, and replace the operator
and two operands by the result in the expression. For example, in the expression
7 3

5 8 +
*
, when we encounter the

, we compute 7

3, then replace the
subexpression 7 3

by 4. The whole expression now looks like 4 5 8 +
*
.
We continue processing from left to right. This time, + is the ﬁrst operator we
encounter. We apply + to the two most recently seen operands, namely 5 and 8,
which gives 4 13
*
. Finally, this expression evaluates to 13
*
4, which is 52.
(Questions on next page)