Infix to Prefix Visualizer
What is Prefix Notation?
Prefix notation (also called Polish Notation) is a way of writing expressions where the operator comes before the operands.
For example, the infix expression 3 + 4 becomes + 3 4 in prefix.
It removes the need for parentheses by using operator order directly.
Infix to Prefix Conversion Steps
- Reverse the infix expression, while keeping the positions of parentheses correct.
- Replace '(' with ')' and vice-versa.
- Convert the reversed expression to postfix using a stack.
- Finally, reverse the postfix expression to get the prefix expression.
Example:
Infix: (A + B) * (C - D)
Step 1: Reverse → (D - C) * (B + A)
Step 2: Convert to postfix → D C - B A + *
Step 3: Reverse → * + A B - C D
Operator Precedence Table
Operator | Meaning | Precedence |
---|---|---|
( ) | Parentheses | Highest |
^ % | Exponentiation / Modulus | 2 |
* / | Multiplication / Division | 3 |
+ - | Addition / Subtraction | 4 (Lowest) |
Note: Higher precedence means the operation will happen first. Exponentiation (^) is evaluated right-to-left, while others are left-to-right.
Visualize the conversion from infix to prefix notation
Conversion Status
Enter an infix expression and click Convert
Stack
Stack is empty
Output
Output will appear here
Prefix Evaluation using Stack
// Prefix Evaluation using Stack (JavaScript)
function evaluatePrefix(expression) {
let stack = [];
// Process expression in reverse order
for (let i = expression.length - 1; i >= 0; i--) {
const char = expression[i];
if (!isNaN(char)) {
stack.push(parseInt(char));
} else {
const a = stack.pop();
const b = stack.pop();
switch(char) {
case '+': stack.push(a + b); break;
case '-': stack.push(a - b); break;
case '*': stack.push(a * b); break;
case '/': stack.push(Math.floor(a / b)); break;
}
}
}
return stack.pop();
}
// Example: "+*235" becomes (2*3)+5 = 11
console.log(evaluatePrefix("+*235")); // Output: 11
Note: Prefix expressions are evaluated right-to-left. Example: "+*235" becomes (2*3)+5 = 11