Monash University > CSSE > CSE1303 > Part A> Pracs > Prac A2

CSE1303 Computer Science
Semester 2, 2003
Part A
Prac A2 : Stacks

This prac covers material from lecture A03 and Tutorial A2.

Project

To write a small calculator program which calculates integer arithmetic expressions involving the operators +, *, -, and /.

Background

We will first assume that the expression will be written in Reverse Polish notation. Reverse Polish notation is useful as it does not require us to use brackets to solve the precedence problems normal "infix" notation has.

The following table illustrates how normal "infix" expressions can be written in Reverse Polish notation:

Infix Reverse Polish
a + b*c a b c * +
a + (b*c) a b c * +
(a + b)*c a b + c *
a*b + c a b * c +
a*(b + c) a b c + *
(a + b)*(c - d) a b + c d - *
(a + b)*(c - d)/(e + f) a b + c d - * e f + /

Note: the variables appear in the same order, and the operators (+, *, -, /) come after the operands (variables) they are operating on, and that no parentheses are needed for expressions in Reverse Polish notation.

In this prac we will use a stack to evaluate the Reverse Polish expressions. The idea is as follows: as each number is read it is pushed onto the stack; when the characters +, -, * or / are read, two numbers are popped off the stack, the operator is applied to them, and the result is pushed back onto the stack; when the character = is read the number on top of stack is popped out and printed; otherwise an error message is printed.

For example the infix expression

is entered as

When 1 and 7 are read they are pushed onto the stack. Then after the character - is read, 1 and 7 are popped off and their difference -6 is pushed onto the stack. Next 4 and 5 are pushed onto the stack, then after the character + is read, they are popped off and replaced by their sum 9. Then after the character * is read 9 and -6 are popped off the stack, and their product -54 is pushed onto the stack. Finally, after the character = is read -54 is popped off the stack and printed.


Preparation (3 marks if completed before class)

The marks for Preparation will be awarded only if the preparation is complete before the start of the class.


Question 1: (1 mark)


Question 2: (3 marks)


Question 3: (3 marks)


Advanced Questions: (2 marks)


[ Top | Home ]

Last modified: Thursday 26 June 2003 14:42:12