Question 10a
Convert the infix expression (A+B*C/D)-(E-F/G) to postfix form using a stack. Evaluate the resultant postfix expression by replacing A,B,C,D,E,F and G with 3,2,4,2,5,8 and 4.
Topics: Infix to postfix conversion, Evaluating postfix expressions
Watch this exact question run
Solution
- Usual precedence: * and / above + and −; all four are left-associative.
Part 1 — convert (A+B*C/D)−(E−F/G) with an operator stack:
| Symbol | Stack | Postfix |
|---|---|---|
| ( | ( | |
| A | ( | A |
| + | ( + | A |
| B | ( + | A B |
| * | ( + * | A B |
| C | ( + * | A B C |
| / | ( + / | A B C * |
| D | ( + / | A B C * D |
| ) | empty | A B C * D / + |
| - | - | A B C * D / + |
| ( | - ( | A B C * D / + |
| E | - ( | A B C * D / + E |
| - | - ( - | A B C * D / + E |
| F | - ( - | A B C * D / + E F |
| / | - ( - / | A B C * D / + E F |
| G | - ( - / | A B C * D / + E F G |
| ) | - | A B C * D / + E F G / - |
| end | empty | A B C * D / + E F G / - - |
Postfix: A B C * D / + E F G / - -
Part 2 — substitute A = 3, B = 2, C = 4, D = 2, E = 5, F = 8, G = 4 and evaluate the postfix form with an operand stack:
| Symbol | Stack | Postfix |
|---|---|---|
| ( | ( | |
| A | ( | A |
| + | ( + | A |
| B | ( + | A B |
| * | ( + * | A B |
| C | ( + * | A B C |
| / | ( + / | A B C * |
| D | ( + / | A B C * D |
| ) | empty | A B C * D / + |
| - | - | A B C * D / + |
| ( | - ( | A B C * D / + |
| E | - ( | A B C * D / + E |
| - | - ( - | A B C * D / + E |
| F | - ( - | A B C * D / + E F |
| / | - ( - / | A B C * D / + E F |
| G | - ( - / | A B C * D / + E F G |
| ) | - | A B C * D / + E F G / - |
| end | empty | A B C * D / + E F G / - - |
| Symbol | Action | Stack |
|---|---|---|
| A | push 3 | 3 |
| B | push 2 | 3 2 |
| C | push 4 | 3 2 4 |
| * | 2 * 4 = 8 | 3 8 |
| D | push 2 | 3 8 2 |
| / | 8 / 2 = 4 | 3 4 |
| + | 3 + 4 = 7 | 7 |
| E | push 5 | 7 5 |
| F | push 8 | 7 5 8 |
| G | push 4 | 7 5 8 4 |
| / | 8 / 4 = 2 | 7 5 2 |
| - | 5 - 2 = 3 | 7 3 |
| - | 7 - 3 = 4 | 4 |
Postfix: A B C * D / + E F G / - - · Result: 4 (integer division)
Check by direct substitution: (3 + 2·4/2) − (5 − 8/4) = (3 + 4) − (5 − 2) = 7 − 3 = 4. All divisions here are exact, so integer and real division give the same answer.
How to write it in the exam
- Postfix: A B C * D / + E F G / − −
- Evaluation: 2·4 = 8, 8/2 = 4, 3 + 4 = 7; 8/4 = 2, 5 − 2 = 3; 7 − 3 = 4.
- Result = 4
How this answer was verified
- tests/linear-expression.test.ts asserts the postfix string and the value 4
- infix_to_postfix.c and postfix_eval.c produce the same output (part of 408 + 400 differential cases)
- Hand check by direct substitution