Presentation is loading. Please wait.

Presentation is loading. Please wait.

Computer Science 2 5/17/2016 Finish the Queue Program

Similar presentations


Presentation on theme: "Computer Science 2 5/17/2016 Finish the Queue Program"— Presentation transcript:

1 Computer Science 2 5/17/2016 Finish the Queue Program
Postfix/Prefix/Infix Stack Calculator

2 Learning Objectives Be able to convert from infix to prefix and postfix notation Be able to evaluate prefix and post fix expressions Push: Use stacks in order to evaluate math expressions in postfix

3 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) ?

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

5 Prefix/Postfix Other Names
Prefix notation was introduced by the Polish logician Lukasiewicz, and is sometimes called “Polish notation”. Postfix notation is sometimes called “reverse Polish notation” or RPN.

6 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!

7 Example infix postfix prefix (a + b) * c a b + c * * + a b c
Infix form : <identifier> <operator> <identifier> Postfix form : <identifier> <identifier> <operator> Prefix form : <operator> <identifier> <identifier>

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

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

10 II. Evaluate the following Postfix expressions (Assume A = 7, B = 4, C = 3, D = -2)
b) A B C D + / * c) A B – C – D – d) A B C D + + -

11 Postfix Calculator If it’s a digit: If it’s an operation: 853+2-+
Push it on the Digit Stack If it’s an operation: Pop two digits from the Digits stack Perform the operation Push the result on to the Digit Stack

12 A VALuable Procedure val(String, RealOrIntegerVariable, IntegerErrorCode); Converts a String into a real or an integer value program test; var error:integer; x:real; number:string; begin writeln('Please enter a number (-1 to quit)'); readln(number); while (number <> '-1') do val(number, x, error); if error = 0 then writeln(x) else writeln('Error !!!'); end; end.

13 Challenge Stack Program
Write a program that will input an addition equation as a string in Postfix notation, and calculate the results. Start with a simple expression and single digit numbers 52+ 63- Then move to more complex expressions 52+3-


Download ppt "Computer Science 2 5/17/2016 Finish the Queue Program"

Similar presentations


Ads by Google