Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
5 views25 pages

DMGT Prefix, Postfix

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views25 pages

DMGT Prefix, Postfix

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 25

Algorithms for Converting Infix

Expressions to Postfix and Prefix


Notations
A comprehensive guide to expression conversion algorithms with detailed step-by-step examples
and practical implementation strategies.
Introduction to Expression Notations
Infix Notation Prefix Notation Postfix Notation
Operators appear between Operators appear before Operators appear after
operands (e.g., A + B). This operands (e.g., + A B). Also operands (e.g., A B +). Also
is the natural way humans known as Polish notation, called Reverse Polish
write mathematical developed by Jan notation, preferred by
expressions. Aukasiewicz. computers.

Computers prefer prefix and postfix notations because they eliminate the need for parentheses and
complex precedence rules during evaluation. Our goal is to systematically convert infix expressions
into these more computer-friendly formats using efficient stack-based algorithms.
Operator Precedence and
Associativity
Parentheses ( )
Highest priority - override all other precedence rules

Exponentiation (^)
Right to left associativity - evaluated from right to left

Multiplication (*) and Division (/)


Left to right associativity - same precedence level

Addition (+) and Subtraction (-)


Left to right associativity - lowest precedence
level

Understanding precedence and associativity is crucial for correct conversion. Parentheses can
override natural precedence to enforce specific evaluation orders, making them essential tools in
complex expressions.
Data Structure: Stack
01 The stack serves as
temporary storage for
Push Operation operators during

Add element to top of conversion processes. It

stack follows the Last-In-First-


Out (LIFO) principle,

02 making it perfect for


managing operator
Pop Operation precedence and handling
nested parentheses
Remove and return top
structures.
element
During conversion, the
03 stack helps us maintain
the correct order of
Peek Operation operations by storing
View top element without operators temporarily
removing until the appropriate time
for output.
Algorithm to Convert Infix to Postfix
01 02

Scan Left to Right Handle Operands


Process each symbol in the infix expression If scanned symbol is an operand, immediately
sequentially from left to right add it to the postfix expression

03 04

Process Opening Parenthesis Process Closing Parenthesis


If scanned symbol is '(', push it onto the stack If scanned symbol is ')', pop and add operators
without any conditions to postfix until '(' is found; discard both
parentheses

05 06

Handle Operators Final Cleanup


Compare precedence with stack top; pop After scanning entire expression, pop all
higher/equal precedence operators to postfix, remaining operators from stack to postfix
then push current operator
Algorithm to Convert Infix to Prefix
Reverse Infix Expression
Write the infix expression backwards, reversing the order of all symbols

Swap Parentheses
Replace every '(' with ')' and every ')' with '(' in the reversed expression

Apply Postfix Algorithm


Use the standard infix-to-postfix conversion algorithm on the modified expression

Reverse Result
Reverse the resulting postfix expression to obtain the final prefix expression

This elegant approach leverages the existing postfix algorithm, making prefix conversion
straightforward and systematic.
Example 1 (Easy):
Infix Expression: A *
B+C/D
Starting Expression Key Learning
Points
A*B+C/D
Multiplication
This is our first example
(*) has higher
demonstrating basic operator
precedence
precedence rules. The
than addition (+)
expression contains
multiplication, addition, and Division (/) has
higher
division operators without
parentheses, making it perfect precedence
than addition (+)
for understanding fundamental
conversion principles. Same
precedence
operators are
evaluated left to
right
Stack manages
operator
ordering
efficiently

We'll convert this expression step-by-step to both


postfix and prefix notations, carefully tracking each
symbol and stack operation.
Example 1: Infix to Postfix Conversion
Table
Step Symbol Action Taken Stack Postfix
Scanned ³
(top bottom) Expression

1 A Operand ³ [] A
Add to postfix

2 * Operator ³ [*] A
Push '*'

3 B Operand ³ [*] AB
Add to postfix

4 + '+' precedence [+] AB*


f '*' ³ Pop '*'
to postfix, push
'+'

5 C Operand ³ [+] AB*C


Add to postfix

6 / '/' precedence [/, +] AB*C


³ Push '/'
> '+'

7 D Operand ³ [/, +] AB*CD


Add to postfix

End End of expr Pop '/' and '+' to [] AB*CD/+


postfix
Example 1: Infix to Prefix Conversion
Steps
Step 1: Reverse Infix 1
Original: A * B + C / D
Reversed: D / C + B * A

2 Step 2: Swap Parentheses


Result: D / C + B * A
(No parentheses to swap in this
Step 3: Convert to Postfix 3 example)
Apply postfix algorithm:
DC/BA*+
4 Step 4: Reverse Result
Final prefix: + * A B / C D

The prefix conversion demonstrates how we can leverage the postfix algorithm with clever
preprocessing and postprocessing steps to achieve the desired result efficiently.
Example 2
(Moderate): Infix
Expression: (A + B) *
(C + D)
Expression Precedence
Analysis Override
(A + B) * (C + D) Parentheses have
highest precedence
This expression
Addition inside
demonstrates how
parentheses must be
parentheses override
completed first
natural operator
precedence. Without Multiplication is
parentheses, performed after both
multiplication would additions
normally be performed Stack handles nested
before addition, but the precedence levels
parentheses force
addition operations to be
completed first.

This moderate-level example showcases the power of


parentheses in expression evaluation and how our stack-
based algorithm elegantly handles precedence
overrides.
Example 2: Infix to Postfix
Conversion Table
Ste Symbol Action Taken Stack Postfix Expression
p

1 ( Push '(' ['(']

2 A Operand ³ Add to postfix ['('] A

3 + Push '+' ['+', '('] A

4 B Operand ³ Add to postfix ['+', '('] AB

5 ) Pop '+' to postfix, pop '(' [] AB+

6 * Push '*' ['*'] AB+

7 ( Push '(' ['(', '*'] AB+

8 C Operand ³ Add to postfix ['(', '*'] AB+C

9 + Push '+' ['+', '(', '*'] AB+C

10 D Operand ³ Add to postfix ['+', '(', '*'] AB+CD

11 ) Pop '+' to postfix, pop '(' ['*'] AB+CD+

End End Pop '*' to postfix [] AB+CD+*


Example 2: Infix to
Prefix Conversion
Steps
Original Infix
(A + B) * (C + D)

Starting expression with parentheses

Step 1: Reverse
)D+C(*)B+A(

Complete reversal of symbols

Step 2: Swap Parentheses


(D+C)*(B+A)

Exchange ( with ) and vice versa

Step 3: Convert to Postfix


DC+BA+*

Apply infix-to-postfix algorithm

Final Prefix Result

*+AB+CD
Example 3 (Moderate): Infix
Expression: A + (B * C - D) / E
Expression Complexity Operation Sequence
A + (B * C - D) / E 1. B * C (highest precedence inside
parentheses)
This expression combines multiple operator types
2. (B * C) - D (subtraction within
with nested operations inside parentheses. It
parentheses)
demonstrates how multiplication, subtraction, and
division interact within a parenthetical grouping, 3. Result / E (division has higher
followed by division and addition operations. precedence than addition)
4. A + final result (addition performed
last)

This example effectively illustrates how parentheses can contain sub-expressions with their own
precedence hierarchies, requiring careful stack management during conversion.
Example 3: Infix to Postfix
Conversion Table
Ste Symb Action Taken Stack Postfix Expression
p ol

1 A Operand ³ Add to postfix [] A

2 + Push '+' [+] A

3 ( Push '(' ['(', '+'] A

4 B Operand ³ Add to postfix ['(', '+'] AB

5 * Push '*' ['*', '(', '+'] AB

6 C Operand ³ Add to postfix ['*', '(', '+'] ABC

7 - '-' precedence f '*' ³ Pop '*', push ['-', '(', '+'] ABC*
'-'

8 D Operand ³ Add to postfix ['-', '(', '+'] ABC*D

9 ) Pop '-' to postfix, pop '(' [+] ABC*D-

10 / '/' precedence > '+' ³ Push '/' ['/', '+'] ABC*D-

11 E Operand ³ Add to postfix ['/', '+'] ABC*D-E

End End Pop '/' and '+' to postfix [] ABC*D-E/+


Example 3: Infix to
Prefix Conversion
Steps
01

Reverse Infix Expression


Original: A + (B * C - D) / E
Reversed: E / ) D - C * B ( + A

02

Swap Parentheses
Before: E / ) D - C * B ( + A
After: E / ( D - C * B ) + A

03

Apply Postfix Algorithm


Process modified expression:
Result: E D C B * - / A +

04

Reverse Final Result


Postfix: E D C B * - / A +
Final Prefix: + A / - * B C D E

The systematic approach ensures correct handling of


complex nested operations while maintaining operator
precedence relationships throughout the conversion
process.
Example 4
(Moderate): Infix
Expression: (A + B) *
(C - D) / (E + F)
(A + B) * (C - D) / (E + F)

1 First Grouping
(A + B) - Addition within first parentheses

2 Second Grouping
(C - D) - Subtraction within second
parentheses

3 Third Grouping
(E + F) - Addition within third parentheses

4 Final Operations
Multiplication then Division - Left to right
evaluation

This expression demonstrates maximum complexity with


three separate parenthetical groupings connected by
multiplication and division. Each parenthetical
expression must be fully evaluated before the
connecting operations can be performed, showcasing
the full power of our conversion algorithms.
Example 4: Infix to Postfix
Conversion Table
S Sy Action Taken Stack Postfix Expression
t mb
e ol
p

1 ( Push '(' ['(']

2 A Operand ³ Add to postfix ['('] A

3 + Push '+' ['+', '('] A

4 B Operand ³ Add to postfix ['+', '('] AB

5 ) Pop '+' to postfix, pop '(' [] AB+

6 * Push '*' ['*'] AB+

7 (C- Process second parenthetical ['*'] AB+CD-


-1 D) group
1

1 / '/' precedence f '*' ³ Pop '*', ['/'] AB+CD-*


2 push '/'

1 (E+ Process third parenthetical ['/'] AB+CD-*EF+


3 F) group
-1
7

E End Pop '/' to postfix [] AB+CD-*EF+/


n
d

Note: Steps 7-11 and 13-17 are condensed for space, showing the complete processing of
parenthetical groups.
Example 4: Infix to Prefix Conversion
Steps
Verification Check
Step 1: Reverse
Original Let's verify our result makes sense:

)F+E(/)D-C(*) * + A B represents (A + B) *
B+A( / - C D represents (C - D) /
+ E F represents (E + F)

Reading prefix from left to right: multiply the


Step 2: Swap result of (A + B) by the result of dividing (C - D)
Parentheses by (E + F), which matches our original infix
expression's intended evaluation order.
(F+E)/(D-C)*(
B+A)

Step 3:
Convert to
Postfix
FE+DC-/BA+*

Step 4: Final
Reverse
*+AB/-CD+EF
Example 5 (Moderate): Infix
Expression: A + B * C - D
Precedence Analysis Natural Evaluation Order
A+B*C-D 1. B * C (highest precedence)
2. A + (B * C) (left-to-right)
This expression tests our understanding of operator
precedence without parentheses. The multiplication 3. Result - D (left-to-right)
operation (* ) has higher precedence than both addition
Without parentheses, natural
(+) and subtraction (-), so B * C must be evaluated first,
operator precedence and
followed by left-to-right evaluation of + and - operations.
associativity rules determine the
evaluation sequence.

This final example demonstrates how our algorithms handle expressions relying entirely on natural
operator precedence, making it an excellent conclusion to our conversion examples.
Example 5: Infix to Postfix
Conversion Table
Step Symbol Action Taken Stack Postfix
Scanned ³
(top bottom) Expression

1 A Operand ³ [] A
Add to postfix

2 + Push '+' [+] A

3 B Operand ³ [+] AB
Add to postfix

4 * '*' precedence ['*', '+'] AB


³ Push '*'
> '+'

5 C Operand ³ ['*', '+'] ABC


Add to postfix

6 - '-' precedence [-] ABC*+


f '*' and '+' ³
Pop both, push
'-'

7 D Operand ³ [-] ABC*+D


Add to postfix

End End of expr Pop '-' to [] ABC*+D-


postfix

Notice how in step 6, both '*' and '+' operators are popped because '-' has equal precedence with '+'
and lower precedence than '*', requiring both to be output before '-' can be pushed onto the stack.
Example 5: Infix to
Prefix Conversion
Steps
Reverse Infix Expression
Original: A + B * C - D
Reversed: D - C * B + A

Check for Parentheses


No parentheses to swap
Proceed with: D - C * B + A

Apply Postfix Conversion


Convert reversed expression:
Result: D C B * - A +

Reverse to Get Prefix


Final prefix expression:
+A-*BCD

This completes our comprehensive set of conversion


examples, demonstrating both simple and complex
scenarios that you'll encounter in practical applications.
Summary of Conversion Algorithms

Stack Management Postfix Algorithm


The stack serves as temporary storage for Scan left-to-right, output operands
operators, ensuring correct precedence immediately, manage operators using stack
ordering during conversion. Push operators based on precedence. Handle parentheses by
based on precedence rules, pop when pushing '(' and popping until '(' when
encountering lower precedence or closing encountering ')'.
parentheses.

Prefix Algorithm Key Principles


Clever approach using double reversal: reverse Operands always output immediately, operators
input, swap parentheses, apply postfix follow precedence rules, parentheses override
algorithm, then reverse result. Leverages natural precedence, and left-to-right scanning
existing postfix logic for consistent results. ensures systematic processing of all
expressions.
Practical Tips for Manual Conversion
Scanning Strategy Stack Visualization
Always scan from left to right for postfix Draw your stack vertically and clearly mark
conversion. Take your time with each the top. Use a table to track each step
symbol and don't rush the process. For systematically. This visual approach
prefix conversion, remember the reverse- prevents errors and makes the process
convert-reverse approach. clearer.

Precedence Memory Verification Methods


Remember PEMDAS: Parentheses, After conversion, evaluate both original and
Exponents, Multiplication/Division, converted expressions with sample values.
Addition/Subtraction. When operators have Check that operator count matches
equal precedence, use left-to-right between infix and postfix/prefix forms.
associativity except for exponentiation.

Practice these techniques with increasingly complex expressions to build confidence and accuracy
in manual conversions.
References and Further Reading

Runestone Academy GeeksforGeeks PrepInsta


Infix, Prefix, and Postfix Convert Infix Expression Infix Prefix Postfix
Expressions to Postfix Conversion

Comprehensive interactive Detailed implementation Step-by-step tutorials with


tutorial with visualizations examples with code in practice problems and
and practice exercises. multiple programming detailed explanations for
languages. interview preparation.
Visit Resource
Visit Resource Visit Resource

These resources provide additional depth, interactive exercises, and programming


implementations to complement the theoretical understanding gained from this document.
Conclusion
Mastering infix to postfix and prefix conversion algorithms represents a fundamental milestone in
understanding expression evaluation and compiler design. These stack-based algorithms
demonstrate elegant solutions to complex precedence management problems that form the
backbone of modern computing systems.

Practical Algorithm Mastery Future Learning


Applications Understanding these These concepts prepare
Calculator algorithms builds you for advanced topics in
implementations, compiler foundation skills in stack compiler construction,
design, programming usage, precedence abstract syntax trees, and
language interpreters, and handling, and systematic expression evaluation
mathematical expression problem-solving optimization.
parsers all rely on these approaches.
conversion techniques.

Through the detailed step-by-step examples provided4from simple expressions like A * B + C / D to


complex nested expressions like (A + B) * (C - D) / (E + F)4you now possess the knowledge and
systematic approach needed to confidently tackle any expression conversion challenge. The
combination of theoretical understanding and practical application ensures you can efficiently
implement these algorithms in real-world scenarios.

Continue practicing with increasingly complex expressions, and consider implementing these
algorithms programmatically to deepen your understanding of their practical applications in
software development and computer science.

Dr. Anita Pisote, Associate Professor, Computer Science & Engineering

You might also like