Convert Infix expression to Postfix expression



Infix to postfix conversion rearranges math expressions to make them easier for computers to evaluate. In infix notation, operators are between operands (e.g., "A + B"). In postfix notation, operators come after operands (e.g., "A B +"). We use a stack to convert infix to postfix, ensuring the order of operations is preserved.

What is Infix, Postfix, and Prefix?

Before jumping into conversion, lets understand the three common types of expressions:

  • Infix: The operator is placed between operands. Example: A + B
  • Postfix (Reverse Polish Notation): The operator comes after the operands. Example: A B +
  • Prefix (Polish Notation): The operator comes before the operands. Example: + A B

Postfix notation is useful because it eliminates the need for parentheses and follows a simple evaluation process using stacks.

Why Use a Stack for Conversion?

Stacks helps us to manage the order of operations (precedence) and parentheses correctly. When scanning an infix expression, we can use a stack to store operators and pop them based on precedence. This way, we can convert infix to postfix without losing the order of operations.

Infix to Postfix Conversion Algorithm

The algorithm for converting an infix expression to a postfix expression using a stack is:

 Read the expression from left to right. 1. If an operand (A-Z, 0-9) is encountered, add it directly to the output. 2. If an operator is encountered: 1. Pop operators from the stack to the output if they have higher or equal precedence. 2. Push the current operator onto the stack. 3. If an opening parenthesis ( is found, push it onto the stack. 4. If a closing parenthesis ) is found, pop operators from the stack to the output until an opening parenthesis is encountered. 5. After scanning the entire expression, pop any remaining operators from the stack to the output. 

Operator Precedence

Operators have different levels of precedence, which determine the order of evaluation:

  • ^ (Exponentiation) Highest precedence
  • *, / (Multiplication, Division) Higher precedence
  • +, - (Addition, Subtraction) Lowest precedence

When two operators have the same precedence, we evaluate them based on associativity. Most operators are left-to-right associative, except exponentiation, which is right-to-left.

Example: Convert Infix to Postfix

Let's convert the infix expression: A + B * C

StepScanned CharacterStackPostfix Expression
1A-A
2++A
3B+A B
4*+ *A B
5C+ *A B C
6--A B C * +

Final Postfix Expression: A B C * +

Evaluating Postfix Expression

Now that we have converted infix to postfix, lets see how to evaluate it:

  • Read the postfix expression from left to right.
  • If an operand is found, push it to the stack.
  • If an operator is found, pop the last two operands from the stack, apply the operation, and push the result back.
  • Continue until the expression is fully processed. The final value in the stack is the result.

Code for Infix to Postfix Conversion

Now that we already know the algorithm, lets see how to implement it in C, C++, Java and Python:

 #include <stdio.h> #include <string.h> #include <ctype.h> #define MAX 100 char stack[MAX]; int top = -1; void push(char item) { if (top == (MAX - 1)) printf("Stack Overflow\n"); else stack[++top] = item; } char pop() { if (top == -1) { printf("Stack Underflow\n"); return '\0'; } return stack[top--]; } int precedence(char symbol) { switch (symbol) { case '^': return 3; case '*': case '/': return 2; case '+': case '-': return 1; default: return 0; } } void infixToPostfix(char infix[], char postfix[]) { int i = 0, j = 0; char symbol; push('('); strcat(infix, ")"); while (infix[i] != '\0') { symbol = infix[i]; if (symbol == ' ') { i++; continue; } if (symbol == '(') push(symbol); else if (isalnum(symbol)) postfix[j++] = symbol; else if (symbol == ')') { while (top != -1 && stack[top] != '(') postfix[j++] = pop(); pop(); } else { while (top != -1 && precedence(stack[top]) >= precedence(symbol)) postfix[j++] = pop(); push(symbol); } i++; } postfix[j] = '\0'; } int main() { char infix[MAX] = "A + B * C"; char postfix[MAX]; printf("Infix Expression: %s\n", infix); infixToPostfix(infix, postfix); printf("Postfix Expression: %s\n", postfix); return 0; } 

Output

Following is the output of the above code:

 Enter Infix Expression: A + B * C Postfix Expression: ABC*+ 
 #include <iostream> #include <stack> #include <string> using namespace std; int precedence(char symbol) { switch (symbol) { case '^': return 3; case '*': case '/': return 2; case '+': case '-': return 1; default: return 0; } } string infixToPostfix(string infix) { stack<char> s; string postfix = ""; s.push('('); infix += ')'; for (int i = 0; i < infix.length(); i++) { char symbol = infix[i]; if (symbol == ' ') continue; if (symbol == '(') s.push(symbol); else if (isalnum(symbol)) postfix += symbol; else if (symbol == ')') { while (s.top() != '(') { postfix += s.top(); s.pop(); } s.pop(); } else { while (precedence(s.top()) >= precedence(symbol)) { postfix += s.top(); s.pop(); } s.push(symbol); } } return postfix; } int main() { string infix = "A + B * C"; cout << "Infix Expression: " << infix << endl; string postfix = infixToPostfix(infix); cout << "Postfix Expression: " << postfix << endl; return 0; } 

Output

Following is the output of the above code:

 Infix Expression: A + B * C Postfix Expression: ABC*+ 
 import java.util.Stack; public class InfixToPostfix { public static int precedence(char symbol) { switch (symbol) { case '^': return 3; case '*': case '/': return 2; case '+': case '-': return 1; default: return 0; } } public static String infixToPostfix(String infix) { Stack<Character> s = new Stack<>(); String postfix = ""; s.push('('); infix += ')'; for (int i = 0; i < infix.length(); i++) { char symbol = infix.charAt(i); if (symbol == ' ') continue; if (symbol == '(') s.push(symbol); else if (Character.isLetterOrDigit(symbol)) postfix += symbol; else if (symbol == ')') { while (s.peek() != '(') { postfix += s.peek(); s.pop(); } s.pop(); } else { while (precedence(s.peek()) >= precedence(symbol)) { postfix += s.peek(); s.pop(); } s.push(symbol); } } return postfix; } public static void main(String[] args) { String infix = "A + B * C"; System.out.println("Infix Expression: " + infix); String postfix = infixToPostfix(infix); System.out.println("Postfix Expression: " + postfix); } } 

Output

Following is the output of the above code:

 Infix Expression: A + B * C Postfix Expression: ABC*+ 
 def precedence(symbol): if symbol == '^': return 3 elif symbol in ['*', '/']: return 2 elif symbol in ['+', '-']: return 1 else: return 0 def infix_to_postfix(infix): stack = [] postfix = "" stack.append('(') infix += ')' for symbol in infix: if symbol == ' ': continue if symbol == '(': stack.append(symbol) elif symbol.isalnum(): postfix += symbol elif symbol == ')': while stack[-1] != '(': postfix += stack.pop() stack.pop() else: while precedence(stack[-1]) >= precedence(symbol): postfix += stack.pop() stack.append(symbol) return postfix infix = "A + B * C" print("Infix Expression:", infix) postfix = infix_to_postfix(infix) print("Postfix Expression:", postfix) 

Output

Following is the output of the above code:

 Infix Expression: A + B * C Postfix Expression: ABC*+ 

Applications of Postfix Notation

Following are some common applications of postfix notation:

  • Used in compilers to evaluate expressions without needing parentheses.
  • Helps in designing calculators where stack-based evaluation is required.
  • Used in Expression Trees for easy computation.

Conclusion

Infix notation is how we naturally write mathematical expressions, but computers prefer postfix because its easier to process. We can use stack for easy Infix to Postfix conversion. Understanding this concept is crucial for solving problems related to expression evaluation and compiler design.

Advertisements
close