# Using a Stack to Evaluate an Expression

Using a Stack to Evaluate an Expression

We often deal with arithmetic expressions written in what is called infix notation:

Operand1 op Operand2

We have rules to indicate which operations take precedence over others, and we often use parentheses to override those rules.

Example: Suppose we have this infix expression Q:

5 * ( 6 + 2 ) – 12 / 4

We can use two stacks to evaluate the expression: a stack for operands, a stack for operators (and parenthesis). We can split the string into array of tokens.

1. While there are still tokens to be read in,

1.1 Get the next token.

1.2 If the token is:

1.2.1 A number: push it onto the value stack.

1.2.2 A variable: get its value, and push onto the value stack.

1.2.3 A left parenthesis: push it onto the operator stack.You can also
choose to push the left parenthesis into the operand stack.

1.2.4 A right parenthesis:

1 While the thing on top of the operator stack is not a

left parenthesis,

1 Pop the operator from the operator stack.

2 Pop the value stack twice, getting two operands.

3 Apply the operator to the operands, in the correct order.

4 Push the result onto the value stack.

2 Pop the left parenthesis from the operator stack, and discard it.

1.2.5 An operator (call it thisOp):

1 While the operator stack is not empty, and the top thing on the

operator stack has the same or greater precedence as thisOp,

1 Pop the operator from the operator stack.

2 Pop the value stack twice, getting two operands.

3 Apply the operator to the operands, in the correct order.

4 Push the result onto the value stack.

2 Push thisOp onto the operator stack.

1. While the operator stack is not empty,

1 Pop the operator from the operator stack.

2 Pop the value stack twice, getting two operands.

3 Apply the operator to the operands, in the correct order.

4 Push the result onto the value stack.

1. At this point the operator stack should be empty, and the value

stack should have only one value in it, which is the final result.

Note: Pay attention to negative operator and parenthesis.

Requirements:

1. Submit the repl.it link of the program

2. Copying code from others or from the Internet is considered as cheating and will result in 0 for the project