Conversion of Arithmetic Expression Using Stack
Stack has various application as we have discussed in the previous post. In this post, we will see how stack is useful to convert the user input expression into a meaningful result.
There are basically three types of expression:
There are basically three types of expression:
- Infix expression
- Postfix expression
- Prefix expression
We generally write any equation in the form of infix expression, but computer system convert this expression into Post-fix or Prefix expression for evaluating the results.
Example: Infix expressions: A+B , X*(Y+Z)
Postfix expression: AB+ , XYZ+*
Prefix expression: +AB, *X+YZ
The transformation of any Infix expression into Postfix expression is performed based on the precedence of the operators.
- The higher precedence operator evaluation is performed first, later the others operators.
- If two operator precedence is equal then we will evaluate the expression left to right, whichever operator coming first evaluate it.
Operator Precedence:
Lets see some examples:
Infix: (A+B)*(C-D)
Postfix: ?
To convert this expression into Postfix, we will use the Stack data structure.
- Scan the expression left to right
- Operator insert into the stack
- Operand write in the Postfix column
- Before insert the operator within the stack check its precedence.
- If higher precedence operator in the stack, then pop the operator first
- Later, Push the lower precedence operator.
Example 1: Infix-> (A+B)*(C-D)
INPUT STACK POSTFIX
Initially Empty Empty
( ( Empty
A ( A
+ (+ A
B (+ AB
) PoP all the Operators before ( AB+
* * AB+
( *( AB+
C *( AB+C
- *(- AB+C
D *(- AB+CD
) PoP all the Operators before ( AB+CD-
PoP * Operator AB+CD-*
_____________________________________________________________________
Example 2: Infix-> A*(B+C)/D
INPUT STACK POSTFIX___
Initially Empty Empty
A Empty A
* * A
( *( A
B *( AB
+ *(+ AB
C *(+ ABC
) PoP all the Operators before ( ABC+
/ Equal precedence Operator Left->Right * is first POP and PUSH / ABC+*
D / ABC+*D
POP / ABC+*D/
______________________________________________________________________
Example 3: Infix-> (A+(B*C))
INPUT STACK POSTFIX____
Initially Empty Empty
( ( Empty
A ( A
+ (+ A
( (+( A
B (+( AB
* (+(* AB
C (+(* ABC
) PoP the operators before ( ABC*
) PoP the Operators before ( ABC*+
________________________________________________________________________
Comments
Post a Comment