Saturday, February 25, 2012

Evaluate Mathematical expressions.

Write a program to evaluate a simple mathematical expression like 4 + 2*a/b - 3 = ((4+(2*(7/2)))-3)


Approach:
Convert the give expression to reverse polish notation.

Expression: ((4+(2*(7/2)))-3)
Reverse polish notation: 4272/*+3-

Now traverse the reverse polish notation from left to right using stack.
When we see a operator while traversing from left to right we pop 2 operand, apply the operator and then push to result onto the stack.
step1: 4 2 7 2 / * + 3 -
first operator seen while traversing left to right is "/". the pop the operands "7" and "2" and apply the operator, result would be "3.5"

step2: 4 2 3.5 * + 3 -
second operator seen is "*", operands are "2" and "3.5", result is "7" - push this to stack.

step3: 4 7 + 3 -
third operator is "+" and operands are "4" and "7", result = 11, push this to stack.

step4: 11 3 -
fourth operator is "-" and operands are "11" and "3", result = 8, push this to stack.
setp5: 8
Now there are no more operators and we are done. 
Final ans is: 8.

Code input/output:

Expression: (2+(3*4))
Reverse polish notation: 234*+
Result:14.0


Expression: ((4+(2*(7/2)))-3)
Reverse polish notation: 4272/*+3-
Result:8.0



No comments:

Post a Comment