Infix to Prefix Conversion and Evaluation
🔶 Infix to Prefix Expression Conversion
✅ Definitions:
-
Infix Expression: Operators are written in-between the operands.Example:
A + B
-
Prefix Expression (Polish Notation): Operators are written before their operands.Example:
+ A B
✅ Why Convert Infix to Prefix?
Computers evaluate prefix or postfix expressions more easily because they don’t need parentheses and respect operator precedence inherently.
✅ Steps to Convert Infix to Prefix:
-
Reverse the infix expression.
-
Change every
(
to)
and vice versa. -
Convert the modified expression to postfix.
-
Reverse the postfix expression to get prefix.
✅ Operator Precedence and Associativity:
Operator | Precedence | Associativity |
---|---|---|
^ | High | Right to Left |
* / % | Medium | Left to Right |
+ - | Low | Left to Right |
✅ Helper Functions:
You’ll need:
-
A function to check if a character is operand.
-
A function to get precedence of operators.
-
A function to convert infix to postfix (used on reversed expression).
-
Stack data structure.
✅ Example 1: Infix to Prefix Conversion
🔸 Infix Expression:
🔹 Step-by-step Conversion:
1. Reverse the Infix Expression:
2. Swap '(' and ')' — not needed here as there are no brackets.
3. Convert Reversed Infix to Postfix:
4. Reverse the Postfix to get Prefix:
✅ Final Prefix Expression:
+A*BC
🔷 Sample C Code for Infix to Prefix Conversion
🔶 Evaluation of Prefix Expression
✅ Steps:
-
Scan prefix expression right to left.
-
If it's an operand, push it on the stack.
-
If it's an operator, pop two operands, apply operator, push result back.
Prefix Expression Evaluation
Let’s evaluate a prefix expression that uses numbers.
🔸 Prefix Expression:
This corresponds to the infix:
🔹 Step-by-step Evaluation:
We process from right to left.
-
Stack:
[]
-
Read
3
→ push → Stack:[3]
-
Read
2
→ push → Stack:[3, 2]
-
Read
*
→ pop 2 and 3 →2 * 3 = 6
→ push → Stack:[6]
-
Read
9
→ push → Stack:[6, 9]
-
Read
+
→ pop 9 and 6 →9 + 6 = 15
→ push → Stack:[15]
Comments
Post a Comment