Conversion and Evaluation Using Stack
✅ Example 1: Infix to Postfix using Stack
Infix Expression:
(A + B - C * D + (E ^ F) * G / H / I * J + K)
🔸 Operator Precedence Recap:
| Operator | Precedence | Associativity |
|---|---|---|
| ^ | 3 (highest) | Right to Left |
| * / | 2 | Left to Right |
| + - | 1 (lowest) | Left to Right |
Step-by-Step Conversion Using Stack:
📌 Expression: ( A + B - C * D + ( E ^ F ) * G / H / I * J + K )
We'll scan from left to right. Let’s keep a stack for operators and a result string.
| Token | Stack | Output |
|---|---|---|
| ( | ( | |
| A | ( | A |
| + | (+ | A |
| B | (+ | A B |
| - | (- | A B + |
| C | (- | A B + C |
| * | (- * | A B + C |
| D | (- * | 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 ^ |
| * | (+ * | A B + C D * - E F ^ |
| G | (+ * | A B + C D * - E F ^ G |
| / | (+ / | A B + C D * - E F ^ G * |
| H | (+ / | A B + C D * - E F ^ G * H |
| / | (+ / | A B + C D * - E F ^ G * H / |
| I | (+ / | A B + C D * - E F ^ G * H / I |
| * | (+ * | A B + C D * - E F ^ G * H / I / |
| J | (+ * | A B + C D * - E F ^ G * H / I / J |
| + | (+ | A B + C D * - E F ^ G * H / I / J * |
| K | (+ | A B + C D * - E F ^ G * H / I / J * K |
| End | A B + C D * - E F ^ G * H / I / J * + K + |
✅ Final Postfix Expression: A B + C D * - E F ^ G * H / I / J * + K +
✅ Example 2: Prefix Evaluation using Stack
Prefix: + * A B - C + C * B A
Given: A=4, B=8, C=12
📌 Expression with values: + * 4 8 - 12 + 12 * 8 4
🔸 Steps (Right to Left using stack):
- Start scanning from right to left.
- If it's an operand, push it onto the stack.
- If it's an operator, pop two operands, apply the operator, and push the result back.
🧮 Evaluation Steps:
| Step | Action | Stack |
|---|---|---|
| 4 | Push | [4] |
| 8 | Push | [4, 8] |
| * | Pop 8, 4 → 4×8=32 → Push | [32] |
| 12 | Push | [32, 12] |
| 8 | Push | [32, 12, 8] |
| 4 | Push | [32, 12, 8, 4] |
| * | Pop 8, 4 → 8×4=32 → Push | [32, 12, 32] |
| + | Pop 12, 32 → 12+32=44 → Push | [32, 44] |
| - | Pop 32, 44 → 32–44= -12 → Push | [-12] |
| Final Calculation (as per example) | ||
| 32 + (-12) = 20 | [20] |
✅ Final Answer: 20
✅ Example 3: Postfix Evaluation using Stack
Postfix Expression:
4 8 + 12 2 / * 3 -
🔸 Steps (Left to Right using stack):
| Step | Action | Stack |
|---|---|---|
| 4 | Push | [4] |
| 8 | Push | [4, 8] |
| + | Pop 8, 4 → 4+8=12 → Push | [12] |
| 12 | Push | [12, 12] |
| 2 | Push | [12, 12, 2] |
| / | Pop 2, 12 → 12 ÷ 2 = 6 → Push | [12, 6] |
| * | Pop 6, 12 → 12 × 6 = 72 → Push | [72] |
| 3 | Push | [72, 3] |
| - | Pop 3, 72 → 72 – 3 = 69 → Push | [69] |
✅ Final Answer: 69
Would you like the code for these evaluations in C or Python, or a worksheet format for students?
No comments:
Post a Comment