Problem 3: Calculator
Background:
A friend would like a simple calculator program written that
will calculate certain expressions. All expressions are postfix
expressions that may or may not be correct (can't expect
your friend to be perfect.)
This calculator has 4 variables, A, B, C, and D. The variables
are initially set to 0. Values can be stored into variables using
the `=' operator (more on that later). Each variable stores
an integer (positive or negative). The calculator is case insensitive
when it comes to variable names. Any other letter is
invalid.
The calculator is to handle the operators +, -, *.
Input:
Each line of input represents one expression/command given
to the calculator. There are no blank lines.
If the first character on the line is `=', then the command
is an assignment. The = will be followed by a space then
by a variable name.
The value of the previous expression is put into the variable.
If the previous expression is udefined, put the value 0 into
the variable.
All other lines are postfix expressions that are to be
evaluated. There will be one space separating the numbers, operands,
or variables. If a valid variable is used in the expression, it's
value is substituted in.
All numbers given to you will be nonnegative integers.
Output:
For each correct postfix expression, your program should print
out the value of the expression.
For each assignment, your program should print the value that
was placed into the variable.
If a postfix expression is invalid, your program should print
one of two things:
- undefined variable -- if the expression uses a bad variable name.
- invalid expression -- otherwise.
If both problems are present, print undefined variable.
If an assignment statment references a bad variable name,
print undefined variable.
After all the input has been processed, you should print
out the final value of each variable in the format var=value.
The variables should be printed in alphabetical order.
Sample Input:
9 + 8
9 8 +
= A
A B +
= C
= F
A B * F +
3 6 + 100 2 - 8 * - 600 + 20 10 * -
Sample Output:
invalid expression
17
17
17
17
undefined variable
undefined variable
-375
A=17
B=0
C=17
D=0