next up previous
Next: About this document Up: My Home Page

Building the Calculator
Lecture 6

Steven S. Skiena

Reverse Polish Notation

HP Calculators use reverse Polish notation or postfix notation. Instead of the conventional a + b, we write A B +.

Our calculator will do the same. Why? Because it is the easiest notation to implement!

displaymath162

The rule for conversion is to read the expression from left to right. When we see a number, push it on the operation stack. When we see an operation, pop the last two numbers on stack, do the operation, and push the result on the stack.

Look Ma, no parentheses!

Algorithms for the calculator

To implement addition, we add digits from right to left, with the carry one place if the sum is greater than 10.

Note that the last carry can go beyond one or both numbers, so you must handle this special case.

To implement subtraction, we work on digits from right to left, and borrow 10 if necessary from the digit to the left.

A borrow from the leftmost digit is complicated, since that gives a negative number.

This is why I suggest completing addition first before worrying about subtraction.

I recommend to test which number has a larger absolute value, subtract from that, and then adjust the sign accordingly.

displaymath163

Parsing the Input

There are several possible ways to handle the problem of reading in the input line and parsing it, i.e. breaking it into its elementary components of numbers and operators.

The way that seems best to me is to read the entire line as one character string in a variable of type TEXT.

As detailed in your book, you can use the function Text.Length(S) to get the length of this string, and the function Text.GetChar(S,i) to retreive any given character.

Useful functions on characters include the function ORD(c), which returns the integer character code of c. Thus ORD(c) - ORD('0') returns the numerical value of a digit character.

You can test characters for equality to identify special symbols.

Standard I/O

The easiest way to read and write from the files is to use I/O redirection from UNIX.

Suppose calc is your binary program, and it expects input from the keyboard and output to the screen. By running calc < filein at the command prompt, it will take its input from the file filein instead of the keyboard.

Thus by writing your program to read from regular I/O, you can debug it interactively and also run my test files.

Programming Hints

  1. Write the comments first, for your sake.
  2. Make sure your main routine is abstract enough that you can easily see what the program does.
  3. Isolate the details of your data structures to a few abstract operations.
  4. Build good debug print routines first.




next up previous
Next: About this document Up: My Home Page

Steve Skiena
Tue Sep 23 16:01:44 EDT 1997