Infix to Postfix/Prefix Converter

The expressions of the form a op b are known as infix expressions. In other words these are the expressions in which the operator is in between the operands. Postfix expression are the expressions which are of the form a b op. In other words the expressions in which the operators are followed by the operands pair is called postfix operation.

Infix to Postfix/Prefix Converter

Enter Infix Expression:



Algorithm for Postfix Conversion:

For the conversion of the infix expression to the postfix expression we use a algorithm stated below:

  • Scan the infix expression from left to right.
  • If the scanned character is an operand, push it to opstack.
  • Else, 1 If the precedence and associativity of the scanned operator is greater than the precedence and associativity of the operator in the stack(or the stack is empty or the stack contains a ‘(‘ ), push it.
  • 2 ‘^’ operator is right associative and other operators like ‘+’,’-‘,’*’ and ‘/’ are left associative. Check especially for a condition when both top of the operator stack and scanned operator are ‘^’. In this condition the precedence of scanned operator is higher due to it’s right associativity. So it will be pushed in the operator stack. In all the other cases when the top of operator stack is same as scanned operator we will pop the operator from the stack because of left associativity due to which the scanned operator has less precedence.
  • 3 Else, Pop all the operators from the stack which are greater than or equal to in precedence than that of the scanned operator. After doing that Push the scanned operator to the stack. (If you encounter parenthesis while popping then stop there and push the scanned operator in the stack.)
  • 4. If the scanned character is an ‘(‘, push it to the stack.
  • 5. If the scanned character is an ‘)’, pop the stack and output it until a ‘(‘ is encountered, and discard both the parenthesis.
  • 6. Repeat steps 2-6 until infix expression is scanned.
  • 7. Print the output
  • 8. Pop and output from the stack until it is not empty.

Algorithm for Prefix Conversion:

    For the conversion of the infix expression to the prefix expression we use a algorithm stated below:

  • Scan the infix expression from left to right.
  • Reverse the expression changing the brackets directions.
  • Using postfix evaluation to the reversed expression
  • Again reverse the result from this evaluation to get the prefix expression.