Week 6 Applications of Stack
Week 6 Applications of Stack
Expression Evaluation
Expression Conversion
• Expression will be given in infix form
• Convert to Prefix
• Convert to Postfix
Infix Notation
Following expressions are infix notation
•2 + 5
• (2 – 1) * 6
Rules
• For expression conversion first we solve Brackets, then we solve
divide, then multiply and at the end for plus and minus we move from
left to right. While moving form left to right if the operator is minus
we solve that first, and if the operator is plus then we solve that first.
And keep moving till end.
Prefix notation
• To convert an infix expression to prefix we will put the operator
before those operands.
Example 1:
Infix= 2 + 6
Prefix= + 2 6
Example 2:
Infix= 2 + 16 * 15
Solution:
2 + * 16 15
+2 * 16 15
Postfix notation
• To convert an infix expression to postfix we will put the operator after
those operands.
Example 1:
Infix= 2 + 6
Prefix= 2 6 +
Example 2:
Infix= 2 + 16 * 15
Solution:
2 + 16 15 *
2 16 15 * +
Q1:Convert the following
expressions to Prefix and evaluate
using stack
20 – 15 / 3 + 13
20 – 15 3 / + 13
20 15 3 / – + 13
20 15 3 / – 13 +
Now evaluate using Stack
20 15 3 / – 13 +
20 is a number, push
into stack
20
Now evaluate using Stack
20 15 3 / – 13 +
15 is a number, push
into stack
15
20
Now evaluate using Stack
20 15 3 / – 13 +
3 is a number, push
into stack
3
15
20
Now evaluate using
Stack
20 15 3 / – 13 +
/ is an operator, pop
the two numbers from
the stack, divide them
and push back the
3 result into the stack
5
15
15 / 3 5
20
20
Now evaluate using
Stack
20 15 3 / – 13 +
- is an operator, pop
the two numbers from
the stack, minus them
and push back the
result into the stack
5
20 - 5 15
15
20
Now evaluate using
Stack
20 15 3 / – 13 +
13 is a number, push
into stack
13
15
Now evaluate using
Stack
20 15 3 / – 13 +
+ is an operator, pop
the two numbers from
the stack, plus them
and push back the
result into the stack
13
15 + 13 28
28
15
Expression Solved
28