Homework 3 - Stacks

Due: Friday April 23, 2010 at 5:00pm

NOTE: No late assignments will be accepted beyond Sunday, April 25th so that the solutions can be posted Monday morning to study before the Midterm on Tuesday, April 27th.

The purpose of this assignment is to implement a template class called Stack which uses a statically sized array to store the stack and implement a postfix expression evaluator with the stack.

This assignment will create a template class called Stack which supports two exception classes called EmptyStack and FullStack. The stack class will use a statically sized array of 100 elements to store the data. It will also need to track the current top of the stack.

Stack will have the following public interface:

Your main function will implement a postfix expression evaluator. A postfix expression is of the following form:
expression expression operator
where expression can be either a numerical literal or another postfix expression. For example, the postfix expression 3 4 + is equal to 3 + 4 and the postfix expression 3 5 + 6 * is equal to (3 + 5) * 6.

Postfix expressions are evaluated by starting at the leftmost variable and working your way to the right. The stack stores the numbers in the expression (you can choose either integers or doubles for your numbers).

The logic for the evaluation is as follows:

while there are still variables from the expression to parse
  if the current variable is a number
    push the number onto the stack
  if the current variable is an operator
    pop the top two values off the stack
    if either pop throws an EmptyStack expression
      print "The postfix expression is invalid"
      return
    perform the given operation with the two values 
    push the result of the operation on the stack
  retrieve the next variable in the expression
end-while

if the stack not empty
  pop the value off the stack
  if the stack is now empty
    print the value as the result of the expression
  else
    print "The postfix expression is invalid"
else
  print "The postfix expression is invalid"
For example, the expression 3 5 + 6 * would put 3 on the stack, then 5 on the stack and then see the + operator. It would then pop 3 and 5 off the stack, add them together and put 8 on the stack. Then it would put the 6 on the stack and then see the * operator. It would then pop 8 and 6 off the stack, multiply them together and put 48 on the stack. It would then exit the while loop and pop the result 48 off the stack.

Your main program should have a do-while loop which asks for a postfix expression, performs the above evalutation and then prompts the user if they wish to enter another expression. This input loop will continue while the user indicates they wish to enter another expression.

Email your completed source code to me.