Infix expression:The expression of the form a op b. When an operator is in-between every pair of operands.
Postfix expression:The expression of the form a b op. When an operator is followed for every pair of operands.
Examples of Infix to Postfix
Let’s consider few examples to elaborate the infix and postfix forms of expressions based on their precedence order:
Infix | Postfix |
A + B 12 + 60 – 23 (A + B)*(C – D ) A B * C – D + E/F | A B + 12 60 + 23 – A B + C D – * A B C*D – E F/+ |
A programmer can write the operators either after the operands i.e. postfix notation or before the operands i.e. prefix notation. Some of the examples are as under:
Infix | Postfix |
A + B | A B + |
12 + 60 – 23 | 12 60 + 23 – |
(A + B)*(C – D ) | A B + C D – * |
A B * C – D + E/F | A B C*D – E F/+ |
• We use a stack
• When an operand is read, output it
• When an operator is read
– Pop until the top of the stack has an element of lower
precedence
– Then push it
• When ) is found, pop until we find the matching (
• ( has the lowest precedence when in the stack
• but has the highest precedence when in the input
• When we reach the end of input, pop until the stack is
empty.
Comments
Post a Comment