University of Calgary

simple calculator

Simple Calculator Program
source: Katrin Becker 2001

[Help] 

[More Help - from the Polish Postfix Assignment. The calculator is essentially the first part of the polish postfix assignment]
Design and implement an Object-Oriented program that will parse and evaluate simple expressions. An expression for our simple calculator can be defined as follows:
<operand> ::= 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 |
<operator> ::= + | - | * | / (binary operators only; evaluated left to right; normal precedence: i.e. */ before +-)
<expression> ::= <operand> | <expression> <operator> <expression> |
        (<expression>)
<statement> ::= <expression>;
 

If the expression given as input is illegal; indicate where the error was found and print an appropriate error message. Implement the program using two stacks: one for operands and one for other tokens.

Testing:

Test your program using at least the following:

5 + (6 - 7);
(3 (2 + 1));
((7 + 6) * (4 + 2));
((7 = 6) * (4 + 2);
;
(3 * (2 + 1));
4 ++ 6;
2 7 3;
(2) + (2);

BONUSES:

1. [2 points] allow operands to be any natural number
2. [4 points] implement unary operators + -
3. [4 points] implement bit wise & | ^ ~ with proper precedence

Full Definition of Expressions adapted from Pascal Language Definition

<unsigned constant> ::= <unsigned number>

<factor> ::= <unsigned constant> | (<expression>)

<term> ::= <factor> | <term> <multiplying operator> <factor>

<simple expression> ::= <term> |

<simple expression> <adding operator> <term> |
<sign> <factor>

<expression> ::= <simple expression>

<multiplying factors> ::= * | /

<adding factors> ::= + | -



Updated: August 31, 2005 01:56 PM