3. Conversion And Evaluation of Expressions
• Stack
A Stack is an ordered list in which all
insertions and deletions are made at one end
called Top.
4. Expressions
Expression is a string of operands and operators.
Operands are some numeric values and operators
are of two types :
Unary operators such as ‘+’ and ‘-’.
Binary operators such as ‘+’, ‘-’, ‘*’, ‘/’ and
exponential.
6. Infix Expressions
• Parenthesis can be used in these expressions.
• Infix expressions are the most natural way of
representing expressions.
Infix expression = Operand1 operator Operand2
Examples: 1) (a+b)
2) (a+b)*(c-d)
3) a+b/c)*(d+f)
7. Postfix Expression
In postfix expression, there are no
parenthesis used. All the corresponding operands
come first and then operator can be placed.
Postfix Expression = Operand1 operand2 operator
Examples:
1) ab+
2) ab+cd-
3) ab+c/df+*
8. Prefix Expression
In prefix expression, there are no
parentheses used. All the corresponding operators
come first and then the operands are arranged.
Prefix Expression = Operator Operand1 Operand2
Examples:
1) +ab
2) *+ab-cd
3) */+abc+df
9. Conversion of Infix to Postfix Expressions:
Eg.: ((a-b)*(a+b))
S.No Input
Character
Stack Postfix Expressions
1. ( (
2. ( ((
3. a (( a
4. - ((- a
5. b ((- ab
6. ) ( ab-
7. * (* ab-
8. ( (*( ab-
9. a (*( ab-a
10. + (*(+ ab-a
11. b (*(+ ab-ab
12. ) (* ab-ab+
13. ) Empty ab-ab+*
The postfix expression is ab-ab+*
10. Conversion of Postfix to Prefix:
Eg.:ABCDE/*-F/G++
Prefix = Operator Operand1 Operand2
Step1: ABCDE/*-F/G++
Step2: ABC(/DE)*-F/G++
Step3: AB(*C/DE)-F/G++
Step4: A(-B*C/DE)F/G++
Step5: A(/-B*C/DEF)G++
Step6: A(+/-B*C/DEFG)+
Step7: +A+/-B*C/DEFG
+A+/-B*C/DEFG is the prefix expression.
11. Conversion of Postfix to Infix form:
Eg.:ABC(DE/*-F/G++
Infix = Operand1 Operator Operand2
Step1: ABCDE/*-F/G++
Step2: ABC/DE*-F/G++
Step3: AB(C*(D/E)-F/G++
Step4: A(-B(C*D/E)))F/G++
Step5: A(((B-(C(D/E)))/F)G++
Step6: A(((B-(C(D/E))/F+G)+
Step7: (A+(B-(C*(D/E)))/F)+G))
(A+(B-(C*(D/E)))/F)+G)) is the infix expression.
12. Evaluation of Expressions
Algorithm:
Add the right paranthesis.
Scan the expressions from left to right of each
element until the closed parenthesis is
encountered.
If operand is encountered, then Push to Stack.
If operator is encountered, then next two
elements from Stack is Poped.
Evaluate the expression with the operator .
E.g.(b*c).
Set the result to the Top of the Stack.
Exit.