Stack Applications: CS501 Irena Pevac
Stack Applications: CS501 Irena Pevac
CS501
Irena Pevac
Arithmetic Expressions
• Arithmetic expressions have
– operands (variables or numeric constants).
– Operators
• Binary : +, -, *, / ,%
• Unary: -
Priority convention:
- Unary minus (sign for negative numbers) has highest
priority
*, /, % have medium priority
+, - have lowest priority
Infix, Prefix, Postfix
• Example: arithmetic expression a & b consists of
operands a, b and operator &.
– Infix notation is format where operator is specified in
between the two operands. a&b
– Prefix notation is format where operator is specified
before the two operands. &ab
– Postfix notation is format where operator is specified
after the two operands. Postfix notation is also called
RPN or Reverse Polish Notation. a b &
Arithmetic Expressions
Prefix Notation Infix Notation Postfix Notation
+A * B C A+B*C ABC*+
( (
7 ( 7
+ (+ 7
1 (+ 71
) 71+
* * 71+
( *( 71+
6 *( 71+6
+ *(+ 71+6
( *(+( 71+6
(7+1)*(6+(3-2)) >> RPN
3 *(+( 71+63
- *(+(- 71+63
2 *(+(- 71+63
) *(+ 71+63-
) * 71+63-+
(7+1)*(6+(3-2)) >> RPN
• 7 1 + 6 3 - + displayed
• Stack content *
• Add that to display
• 7 1 + 6 3 - + * is RPN
Checking Parenteses
• Create an empty stack
• Until a special symbol appears (indicating the end of
expression) do
Read one by one token from the input expression
If token is
{ If the stack is empty push token to the stack
If the stack is non empty pop a top stack element
If the popped element is ( or [ type an error message such as
“Rule 2 is not satisfied at position…”
Otherwise push it back and push the token to the stack.
[ …
( …
Checking Parenteses
} If the stack is empty rule 1 is not satisfied. Type a message …
If the stack is not empty pop the top stack element and
If it is { then read next token
Otherwise type “Rule 1 is not satisfied at position …
] …
) …
Other Skip to the next token
• If the stack is non empty after the end of expression has
been encountered then print an error message such as
“Rule 1 is violated at the end of expression”
else ”Check control is O.K.”