CS 1723 Section 1T, Summer 1998 Assignment 5

Write an integer expression evaluator in C. Your program should read in an expression from standard input and print the value of the expression on standard output. Expressions may operators for multiplication (*), addition (+), division (/), subtraction (-), and modulis (%). Parentheses are allowed in expressions. Non-negative integer constants are also allowed in expressions (you may do negative constants as well, though it isn't required).

Write a recursive descent parser similar to the example in lecture 7. You should have six kinds of nodes in the parse tree:

Note that the parser for Boolean expressions in lecture 7 has a higher priority for AND than for OR. Similarly, your parser should place a higher priority on *, / and % than on + or -. A grammar describing this parser is given by:
expr : sum
sum : product { "+" sum } | { "-" sum }
product : parenexpr { "*" product } | { "/" product } | { "%" product }
parenexpr: constant | "(" expr ")"
constant: an integer constant You may refer to parts of the parser presented in lecture 7 for ideas about how to divide expressions into operators and constants, how to write a recursive descent parser, and how to evaluate expressions.

Test your program on a variety of inputs. Here are some examples, with the desired result:

input: 1 + 2 + 3 + 4
output: 10

input: (100 + 200) * 300
output: 90000

input: 100 + 200 * 300
output: 60100

input: ((2 + 3) % 3) / ((4 - 2) * (10 / (5 * 2)))
output: 1

input: 2 + 3 )
output: "parse error"
On Unix, there is a program called bc that accepts (among other things) expressions of this type and evaluated them. You can use it to verify the output of your program.

You may write your program anywhere, but it should compile and work on runner since this is where it will be tested. It should:

  1. Prompt for and read in an expression from standard input, or exit if standard input is at end of file. The end of an expression is signaled by the end-of-line character, '\n' (e.g., the user pressed ENTER).
  2. Print the result of evalulating the expression on standard output.
  3. Continue processing at step 1.
If an expression fails to be parsed correctly, your program should give an error message like "parse error" and then exit. It should not cause an access violation or other runtime error.

This program is due by midnight, July 7, 1998. Details of how to turn it in will be given in class.