beautypg.com

Example program - a rpn calculator – HP Integrity NonStop H-Series User Manual

Page 112

background image

Example Program - A RPN Calculator

A classic application of a stack is in the implementation of calculator. Input to the calculator
consists of a text string that represents an expression written in reverse polish notation (RPN).
Operands, that is, integer constants, are pushed on a stack of values. As operators are encountered,
the appropriate number of operands are popped off the stack, the operation is performed, and the
result is pushed back on the stack.

Obtaining the Sample Program

We can divide the development of our stack simulation into two parts, a calculator engine and a
calculator program. A calculator engine is concerned with the actual work involved in the
simulation, but does not perform any input or output operations. The name is intended to suggest an
analogy to a car engine, or a computer processor - the mechanism performs the actual work, but the
user of the mechanism does not normally directly interact with it. Wrapped around this is the
calculator program, which interacts with the user, and passes appropriate instructions to the
calculator engine.

We can use the following class definition for our calculator engine. Inside the class declaration we
define an enumerated list of values to represent each of the possible operators that the calculator is
prepared to accept. We have made two simplifying assumptions: all operands will be integer values,
and we will handle only binary operators.

class calculatorEngine {
public:
enum binaryOperator {plus, minus, times, divide};

int currentMemory () // return current top of stack
{ return data.top(); }

void pushOperand (int value) // push operand value on to stack
{ data.push (value); }

void doOperator (binaryOperator); // pop stack and perform
// operator

protected:
stack< int, vector > data;
};

Defensive Programming

The member function doOperator() performs the actual work. It pops values from the stack,
performs the operation, then pushes the result back onto the stack.

void calculatorEngine::doOperator (binaryOperator theOp)
{
int right = data.top(); // read top element
data.pop(); // pop it from stack

This manual is related to the following products: