0% found this document useful (0 votes)
52 views8 pages

Arithmetic Expressions: - Infix Form

The document discusses arithmetic expressions in infix, postfix, and prefix forms. It explains how to evaluate postfix expressions using a stack, with operands being pushed onto the stack and operators popping the top two operands and pushing the result. An example is provided of evaluating the postfix expression "598+46**7+*" step-by-step using a stack.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
52 views8 pages

Arithmetic Expressions: - Infix Form

The document discusses arithmetic expressions in infix, postfix, and prefix forms. It explains how to evaluate postfix expressions using a stack, with operands being pushed onto the stack and operators popping the top two operands and pushing the result. An example is provided of evaluating the postfix expression "598+46**7+*" step-by-step using a stack.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 8

Arithmetic Expressions

Infix form
operand operator operand
2+3 or
a+b
Need precedence rules
May use parentheses
4*(3+5) or
a*(b+c)
Arithmetic Expressions
Postfix form
Operator appears after the operands
(4+3)*5 : 4 3 + 5 *
4+(3*5) : 4 3 5 * +
No precedence rules or parentheses!
Input expression given in postfix form
How to evaluate it?
Evaluating Postfix Expressions
Use a stack, assume binary operators +,*
Input: postfix expression
Scan the input
If operand,
push to stack
If operator
pop the stack twice
apply operator
push result back to stack
Example
Input
598+46**7+*
Evaluation
push(5)
push(9)
push(8)
push(pop() + pop()) /* be careful for - */
push(4)
push(6)
push(pop() * pop())
push(7)
push(pop() + pop())
push(pop() * pop())
print(pop())
What is the answer?
Exercise
Input
6523+8*+3+*
Input
abc*+de*f+g*+
For each of the previous inputs
Find the infix expression
Infix to Postfix Conversion
Observation
Operands appear in the same order in both
Output operands as we scan the input
Must put operators somewhere
use a stack to hold pending operators
) indicates both operands have been seen
Will allow only +, *, (, and ), and use
standard precedence rules
Assume legal (valid) expression
Conversion Algorithm
Output operands as encountered
Stack left parentheses
When )
repeat
pop stack, output symbol
until (
( is poped but not output
If symbol +, *, or (
pop stack until entry of lower priority or (
( removed only when matching ) is processed
push symbol into stack
At end of input, pop stack until empty
Exercises
(5 * (((9 + 8) * (4 * 6)) + 7))
6 * (5 + (2 + 3) * 8 + 3)
a + b * c + (d * e + f) * g

You might also like