Saturday, 26 July 2025

Polish Notation: Conversion and Evaluation Examples

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
EndA 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
4Push[4]
8Push[4, 8]
*Pop 8, 4 → 4×8=32 → Push[32]
12Push[32, 12]
8Push[32, 12, 8]
4Push[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
4Push[4]
8Push[4, 8]
+Pop 8, 4 → 4+8=12 → Push[12]
12Push[12, 12]
2Push[12, 12, 2]
/Pop 2, 12 → 12 ÷ 2 = 6 → Push[12, 6]
*Pop 6, 12 → 12 × 6 = 72 → Push[72]
3Push[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

The Building Blocks of IoT: Embedded Devices, Sensors, and Actuators 🧠 The Building Blocks of IoT: Embedded D...

Popular Posts