# INFIX, PREFIX, & POSTFIX EXPRESSIONS. Infix Notation We usually write algebraic expressions like this: a + b This is called infix notation, because the.

## Presentation on theme: "INFIX, PREFIX, & POSTFIX EXPRESSIONS. Infix Notation We usually write algebraic expressions like this: a + b This is called infix notation, because the."— Presentation transcript:

INFIX, PREFIX, & POSTFIX EXPRESSIONS

Infix Notation We usually write algebraic expressions like this: a + b This is called infix notation, because the operator (+) is inside the expression A problem is that we need parentheses or precedence rules to handle more complicated expressions: For Example : a + b * c = (a + b) * c ? = a + (b * c) ?

Infix, Postfix, & Prefix notation There is no reason we cant place the operator somewhere else. How ? Infix notation : a + b Prefix notation : + a b Postfix notation: a b +

Other Names Prefix notation was introduced by the Polish logician Lukasiewicz, and is sometimes called Polish notation. Postfix notation is sometimes calledreverse Polish notation or RPN.

Why ? Question: Why would anyone ever want to use anything so unnatural, when infix seems to work just fine? Answer: With postfix and prefix notations, parentheses are no longer needed!

Example infix postfix prefix (a + b) * c a b + c * * + a b c a + (b * c) a b c * + + a * b c Infix form : Postfix form : Prefix form :

Operator priority

Converting Infix to Postfix & Prefix

Example

Infix to Postfix Conversion Algorithm else // ch must be some other operator { while operator stack not empty and precedence(top(S)) precedence(ch) and top(S) != ( do pop operator; append it to the postfix string; end while; push S } end for; while operator stack is not empty do pop operator; append it to the postfix string; endwhile; given a legal infix string; create an initially empty postfix string; create an initially empty operator stack S; for each symbol ch in the infix string do if ch is an operand then append it to the output postfix string; else if ch == ( then push ch onto stack S; else if S == ) then pop and append operators to output string until the matching ( is encountered; // discard the two parentheses

Evaluating Postfix Expression

Infix to Prefix Conversion algorithm#1

Infix to Prefix Conversion algorithm#1 Example

Infix to Prefix Conversion algorithm#2

Evaluating Prefix Expression

Convert from Infix to Prefix and Postfix (Practice) x x + y (x + y) - z w * ((x + y) - z) (2 * a) / ((a + b) * (a - c))

Convert from Postfix to Infix (Practice) 3 r - 1 3 r - + s t * 1 3 r - + + v w x y z * - + *

Similar presentations