Infix and postfix expressions
In a postfix expression,
• an operator is written after its operands.
• the infix expression 2+3 is 23+ in postfix notation.
• For postfix expressions, operations are performed in the order in which they are
written (left to right).
• No parentheses are necessary. ‘
• the infix expression 2+3*4 is 234*+ in postfix notation
• the infix expression 3*4+2*5 translates to 34*25*+ in postfix notation.
• the infix expression 3*(4+2)*5 translates to 342+*5*
Evaluation of postfix expressions.
2+3*4 (infix) / 234*+ (postfix) expression. Notice:
• the operands (2,3,and 4) appear in the same order in both expressions.
• in the postfix version the operators ( * and +) appear in the order in which they
are performed -- the multiplication before the addition
• writing the operators in the order in which they are performed makes postfix
expressions easy to evaluate using the following algorithm:
1. scan the expression, left to right, until you encounter an operator, @
(@ means + - * or /)
2. Perform the operation @. The operands precede the operator
3 4 + = 3+4= 7
3. In the expression, replace @ and its operands with the computed value
4. repeat 1-3 the process until no more operators exist.
Look at 234*+.
Here is the sequence of operations:
• 2 3 4 * + * is the first operator. Perform the operation 34*
• 2 12 + 3 4*is replaced by 12 , the value of 3*4
+ is next operator, perform 2 12+
• replace 2 12+ with 14. Done
The value of the expression is 14. Another example, 3 4 * 2 5 * + which in infix
notation is 3*4 + 2*5.
3 4 * 2 5 * + * is the first operator 3 4 * is replaced by 12
12 2 5 * + 2 5 * is replaced by 10
12 10 + 12 10 + is replaced by 22
22
Postfix notation does not require parentheses.
Evaluation of postfix with a stack"
• Scan the string left to right.
• When you encounter an operand push it on the stack;
• when you encounter an operator, pop the corresponding operands off the stack,
• perform the operation, and push the result back on the stack.