Converting and Evaluating Infix
Converting and Evaluating Infix
Consider a situation where you are writing a programmable calculator. If the user types in 10 + 10, how would you compute a result of the expression? You might have a solution for this simple expression. But what if he types in
3 * 2 / (5 + 45) % 10?
Now let's take a slightly complicated expression : A + B / C How do we convert this infix expression into postfix? To convert A + B / C into postfix, we convert one operation at a time. The operators with maximum priority are converted first followed by those which are placed lower in the order. Hence, A + B / C can be converted into postfix in just X steps. :: A + B / C (First Convert B / C -> B C /) 1: A + B C / (Next Operation is A + (BC/) -> A BC/ + 2: A B C / + (Resultant Postfix Form) The same procedure is to be applied to convert infix into prefix except that during conversion of a single operation, the operator is placed before the two operands. Let's take the same example and convert it to Prefix Notation. :: A + B / C (First Convert B / C -> / B C) 1: A + / B C (Next Operation is A + (/BC) -> + A /BC + 2: + A / B C
Sometimes, an expression contains parenthesis like this: A + B * ( C + D ) Parenthesis are used to force a given priority to the expression that it encloses. In this case, C+D is calculated first, then multiplied to B and then added to A. Without the parenthesis, B * C would have been evaluated first. To convert an expression with paranthesis, we first convert all expressions that are enclosed within the simple brackets like this: [INFIX TO POSTFIX] :: A + B * ( C + D ) 1: A + B * C D + 2: A + B C D + * 3: A B C D + * +