CSS 502 Programming Assignment #1
CSS 502 Programming Assignment #1
PART 1 (programming):
Write a program to evaluate a prefix expression and to convert a prefix expression to postfix using recursion. You may
assume each expression is a valid prefix expression where the operands consist of just one digit and the operators are
either + ,- , *, / . For simplicity, use integer arithmetic (answer is an int). E.g., (3+4)/2 which is /+342 in prefix
notation, results in the answer of 3 and is 34+2/ in postfix notation.
In the data, there is one prefix expression per line. You can assume valid prefix expressions with single digit operand.
For example, with the sample input the sample output looks as
+23 Prefix Expression = Answer
-+231 --------------------------
*+51-24 +23 = 5 As postfix: 23+
/*+91-42+53 -+231 = 4 As postfix: 23+1-
*+51-24 = -12 As postfix: 51+24-*
/*+91-42+53 = 2 As postfix: 91+42-*53+/
Notes
-- To evaluate a prefix expression, the key to the recursion is that every prefix expression is made up of an operator
followed by 2 operands and each of the operands is itself a prefix expression. The simplest of prefix expressions is a
single digit (number). The function isdigit() is useful for determining if a char is a digit or not. The recursive solution
to convert a prefix expression to postfix is similar to evaluating a prefix expression.
-- While it is still object-oriented, the assignment focus is on recursion. The prefix expression is stored in an array.
The function to evaluate itself is very short. If you are doing a lot of work, then you are doing it incorrectly. At the
beginning of the recursive routine, the next symbol in the expression is considered.
-- The type char can also be treated as an int. If you assign a char to an int, it will yield the ascii value. For example,
int i = 'a'; gives i the ascii value of 97. So, you can turn a char '2' into an int 2 using the code i = ch - '0';
The difference in ascii values (which you don't even need to know) of character '2' and character '0' is integer 2.
-- So that you don't get hung up on the reading, all the reading and printing for the assignment is given. You can find
main and a partial Prefix class linked off the assignments page. You wont do any other reading than what is given. So
that the given main works properly, be sure in your data files on a PC, the cursor is on the line following the last
expression. When you're solving this problem, all that is left is the recursion so you can focus on the recursive
problem solving. Think high-level to solve this program. Focus on prefix expressions, not the array.
The loop in main handles one file's worth of prefix expressions. One call to evaluatePrefix deals with one line of data,
one prefix expression. The eof function is true when the EOF character is read, so we read beyond the last
expression to know that it is end-of-file.