[   ^ to index...   |   <-- previous   ]

Recursion exercise (solution...)

Consider the problem of evaluating properly parenthesized binary expressions:

( ( 1 + 2 ) + ( ( 3 - 4 ) + 5 ) )

We can formulate this problem recursively:

    To evaluate an expression,
  1. Read a token. If it is a number, return that number; otherwise, if it is a left parenthesis, continue.
  2. Evaluate an expression.
  3. Read an operator.
  4. Evaluate another expression.
  5. Read a right parenthesis.
  6. Return the value of steps 2, 3, and 4

Assuming there are spaces between each token, we can use cin >> to read the expression and parse it quite easily. Write the evaluate function that will read a line of input, formatted as above, and return an integer. Assume I have provided the functions stringIsNumber() and stringToInt() that will turn a string into a number, if it is a number:

For simplicity (ha), consider only + and -.

bool stringIsNumber(char input[]); int stringToInt(char number[]); int evaluate() { }

Last modified: Tue Jul 11 13:32:09 PDT 2000