Generally arithmetic expressions are written in infix expression where the operator is written between the operands.
Point to consider
- Permitted operands: A, B, C, D means any real number is permitted.
- Permitted operators: +,-, *, /, ^(exponentiation)
- Blanks are permitted in the expression
- Parenthesis are permitted
Suppose given infix expression is
A+B*C-D
where A,B,C,D are operands and +,*,- are operators.
To solve the above infix expression we will use two stack
Operand Stack : This stack will hold operands.
Operator Stack : This stack will hold operators.
Algorithm to evaluate infix expression
Until the end of the expression is reached, get one character and perform only one of the steps (1) through (5):
- If the character is an operand, push it onto the operand stack.
- If the character is “(“, then push it onto the operator stack.
- If the character is “)”, then “process” as explained above until the corresponding “(” is encountered in the operator stack. At this stage POP the operator stack and ignore “(.”
- If we encounter an operator
- If the operator stack is empty then push the operator onto the operator stack.
- If the operator stack is not empty and the operator’s precedence is greater than the precedence of the stack top of the operator stack, then push the character onto the operator stack.
- If the operator stack is not empty and the character’s precedence is lower than the precedence of the stack top of operator stack then we pop the operator with high precedence, and two values from the value stack, apply the operator to the values and store the result in the value stack. And, push the current iterated operator in the operator stack.
- Once we have iterated the entire expression, we pop one operator from the operator stack and two values from the value operator and apply the operator to the values, store the result in the value stack, and keep on repeating this, until we have just a single value left in the value stack.
- The last value in the value stack will be the result.
[wpusb]