Write a Program to Convert Expression from Infix to Postfix using JavaScript in Compiler Design
This article presents a JavaScript program that converts infix expressions to postfix notation. We'll explore the theory behind infix and postfix notations, delve into the code implementation, and provide input/output examples.
Infix & Postfix Notation:
Infix notation is the traditional way of representing expressions, where operators are placed between operands. For example, the infix expression "(2 + 3)" denotes the addition of 2 and 3.
On the other hand, postfix notation, also known as Reverse Polish Notation (RPN), is an expression format where operators follow their respective operands. For the same addition operation, the postfix expression would be "2 3 +".
Converting an infix expression to postfix notation involves rearranging the operators based on their precedence and associativity rules. The process typically utilizes a stack to hold operators temporarily.
Convert Expression from Infix to Postfix in JavaScript:
Let's explore the JavaScript code that converts infix expressions to postfix notation:
function precedence(c) {
if (c == '^') {
return 3;
}
else if (c == '/' || c == '*') {
return 2;
}
else if (c == '+' || c == '-') {
return 1;
}
else {
return 0;
}
}
function isOperand(c) {
if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9')) {
return 1;
}
return 0;
}
function infixToPostfix(infix) {
let stack = [];
let postFix = "";
for (let i = 0; i < infix.length; i++) {
if (isOperand(infix[i])) {
postFix += infix[i];
}
else if (infix[i] == '(') {
stack.push('(');
}
else if (infix[i] == ')') {
while (stack[stack.length - 1] != '(') {
postFix += stack[stack.length - 1];
stack.pop();
}
stack.pop();
}
else {
while (stack.length != 0 && precedence(infix[i]) <= precedence(stack[stack.length - 1])) {
postFix += stack[stack.length - 1];
stack.pop();
}
stack.push(infix[i]);
}
}
while (stack.length != 0) {
postFix += stack[stack.length - 1];
stack.pop();
}
return postFix;
}
let infix = "(A+B)*(c/d)+2";
console.log(`The given infix expression is: ${infix}`);
console.log(`The corresponding postfix expression is: ${infixToPostfix(infix)}`);
0 Response to Write a Program to Convert Expression from Infix to Postfix using JavaScript in Compiler Design
Post a Comment