c que 3
c que 3
To convert infix to postfix, we use a stack to help reorder the operators and operands.
Operator Precedence:
• ^ (exponentiation) > * (multiplication) = / (division) > + (addition) = - (subtraction)
• Operators with equal precedence (like * and /) are processed based on associativity: * and
/ are left-associative.
• Step-by-step conversion:
• Operand A → Add to the output: A
• Operator + → Push onto stack: +
• Operand B → Add to the output: A B
• Operator * → Push onto stack: + *
• Open parenthesis ( → Push onto stack: + * (
• Operand C → Add to the output: A B C
• Operator - → Push onto stack: + * ( -
• Operand D → Add to the output: A B C D
• Close parenthesis ) → Pop until (, output -, stack becomes + *
• End of expression → Pop remaining operators: + * -
• Postfix expression: A B C D - * +
Algorithm to Evaluate Postfix Expression
1. Initialize an empty stack.
2. Scan the postfix expression from left to right:
• If the character is an operand, push it onto the stack.
• If the character is an operator, pop two operands from the stack, apply the operator,
and push the result back onto the stack.
3. At the end of the expression, the stack will contain the result.
// Stack functions
void initStack(Stack *s) {
s->top = -1;
}
// Operator precedence
int precedence(char op) {
if (op == '^')
return 3;
if (op == '*' || op == '/')
return 2;
if (op == '+' || op == '-')
return 1;
return 0;
}
while (!isEmpty(&s)) {
postfix[k++] = pop(&s); // Pop remaining operators from stack
}
postfix[k] = '\0';
}
int main() {
char infix[MAX], postfix[MAX];
return 0;
}
Example Execution:
Input:
Enter infix expression: A + B * ( C - D )
Output:
Postfix expression: ABCD-*+
Result of postfix evaluation: 14
In this case, if A=2, B=3, C=5, and D=1, the result of A + B * ( C - D ) evaluates to 2 + 3
* (5 - 1) = 14.