Question

In: Computer Science

C++ OOP Make a program to evaluate infix arithmetic expressions containing integer operands and the operators...

C++ OOP

Make a program to evaluate infix arithmetic expressions containing integer operands and the operators + (addition), - (subtraction), * (multiplication), / (division) and pairs of parentheses, properly nested. Use the following two-stack algorithm (by E. W. Dijkstra):

  • If the next token in the expression is an integer, push the integer onto the value stack.
  • If the next token in the expression is an operator,
    • If the operator stack is empty or the priority of the operator is greater than the priority of the operator at the top of the operator stack, push the operator onto the operator stack.
    • Otherwise pop an operator and two integers; push the result of applying that operator to those integers onto the value stack. Then decide again what to do with the operator at the next token.
  • If the token in the expression is a left parenthesis, push it onto the operator stack.
  • If the next token in the expression is a right parenthesis: pop an operator and two integers; push the result of applying that operator to those integers onto the value stack. Continue until the top of the operator stack is a left parenthesis. Then pop the left parenthesis and ignore the right parenthesis.
  • At the end of the expression, operators are popped off and evaluated (popping the operands and pushing the results) until the operator stack is empty
    • At this point, the operand stack should have exactly one number in it – the result of the evaluation of the expression.

Provide a user-friendly way to enter expressions to be evaluated.

Please add a comment explaining each step of your program.

Solutions

Expert Solution

#include <bits/stdc++.h>
using namespace std;

// Function to find precedence of 
// operators.
int precedence(char op){
    if(op == '+'||op == '-')
    return 1;
    if(op == '*'||op == '/')
    return 2;
    return 0;
}

// Function to perform arithmetic operations.
int applyOp(int a, int b, char op){
    switch(op){
        case '+': return a + b;
        case '-': return a - b;
        case '*': return a * b;
        case '/': return a / b;
    }
}

// Function that returns value of
// expression after evaluation.
int evaluate(string tokens){
    int i;
    
    // stack to store integer values.
    stack <int> values;
    
    // stack to store operators.
    stack <char> ops;
    
    for(i = 0; i < tokens.length(); i++){
        
        // Current token is a whitespace,
        // skip it.
        if(tokens[i] == ' ')
            continue;
        
        // Current token is an opening 
        // brace, push it to 'ops'
        else if(tokens[i] == '('){
            ops.push(tokens[i]);
        }
        
        // Current token is a number, push 
        // it to stack for numbers.
        else if(isdigit(tokens[i])){
            int val = 0;
            
            // There may be more than one
            // digits in number.
            while(i < tokens.length() && 
                        isdigit(tokens[i]))
            {
                val = (val*10) + (tokens[i]-'0');
                i++;
            }
            
            values.push(val);
            
            // right now the i points to 
            // the character next to the digit,
            // since the for loop also increases 
            // the i, we would skip one 
            // token position; we need to 
            // decrease the value of i by 1 to
            // correct the offset.
            i--;
        }
        
        // Closing brace encountered, solve 
        // entire brace.
        else if(tokens[i] == ')')
        {
            while(!ops.empty() && ops.top() != '(')
            {
                int val2 = values.top();
                values.pop();
                
                int val1 = values.top();
                values.pop();
                
                char op = ops.top();
                ops.pop();
                
                values.push(applyOp(val1, val2, op));
            }
            
            // pop opening brace.
            if(!ops.empty())
            ops.pop();
        }
        
        // Current token is an operator.
        else
        {
            // While top of 'ops' has same or greater 
            // precedence to current token, which
            // is an operator. Apply operator on top 
            // of 'ops' to top two elements in values stack.
            while(!ops.empty() && precedence(ops.top())
                                >= precedence(tokens[i])){
                int val2 = values.top();
                values.pop();
                
                int val1 = values.top();
                values.pop();
                
                char op = ops.top();
                ops.pop();
                
                values.push(applyOp(val1, val2, op));
            }
            
            // Push current token to 'ops'.
            ops.push(tokens[i]);
        }
    }
    
    // Entire expression has been parsed at this
    // point, apply remaining ops to remaining
    // values.
    while(!ops.empty()){
        int val2 = values.top();
        values.pop();
                
        int val1 = values.top();
        values.pop();
                
        char op = ops.top();
        ops.pop();
                
        values.push(applyOp(val1, val2, op));
    }
    
    // Top of 'values' contains result, return it.
    return values.top();
}

int main() {
    cout << evaluate("100 * ( 2 + 12 ) / 14");
    return 0;
}

what is wrong??


Related Solutions

Consider simple infix expressions that consist of single-digit operands; the operators +, -, *, and /;...
Consider simple infix expressions that consist of single-digit operands; the operators +, -, *, and /; and the parentheses. Assume that unary operators are illegal and that the expression contains no embedded spaces. Design and implement a class of infix calculators. The class should have the following members: Private members: a string to store an infix expression for evaluation. a private member function that checks if an infix expression is well formed. (A well formed expression consists of single-digit operands;...
Consider simple infix expressions that consist of single-digit operands; the operators +, -, *, and /;...
Consider simple infix expressions that consist of single-digit operands; the operators +, -, *, and /; and the parentheses. Assume that unary operators are illegal and that the expression contains no embedded spaces. Design and implement a class of infix calculators. The class should have the following members: Private members: a string to store an infix expression for evaluation. a private member function that checks if an infix expression is well formed. (A well formed expression consists of single-digit operands;...
C++ Data Structure Write a program to change following infix expressions to postfix expressions using a...
C++ Data Structure Write a program to change following infix expressions to postfix expressions using a stack a) D-B+C b) C*D+A*B c) (A*B)*C+D*F-C d) (A-4*(B-C)-D/E)*F
Using a stack, write a program that turns a simple infix arithmetic expression into a postfix...
Using a stack, write a program that turns a simple infix arithmetic expression into a postfix expression. For example, 1 + 2 * 3 becomes 2 3 * 1 +. Also, evaluate the expression to ensure the expression is correct.
using python without external libaries Using integer arithmetic operators '+' and '-', print all combinations that...
using python without external libaries Using integer arithmetic operators '+' and '-', print all combinations that sum up to 'sum' by inserting the operators between digits in 'number'. example for 'number=123456789' and 'sum = 0' Print the output using the terminal: Output should be exactly like this from 1 - 22 1 : +1+2-34-56+78+9=0 2 : +1-2-34+5+6+7+8+9=0 3 : +1-23-4-56-7+89=0 ... 12 : -1+2+34-5-6-7-8-9=0 13 : -1+23+4+56+7-89=0 14 : -1-2+34+56-78-9=0 ... 22 : -12-34+56+7-8-9=0
C++ PROGRAMING Implement a program to evaluate simple mathematical expressions. Assume that the original expression is...
C++ PROGRAMING Implement a program to evaluate simple mathematical expressions. Assume that the original expression is provided to the program as a text string. Allowed expression tokens: brackets “(” and “)”, integers like “4”, “15”, addition “+”, subtraction “-”, multiplication “*”, division “/”. Output can be float. Trim spaces from an expression. Brackets should contain at least one operation. Make sure that an expression is validated before it is calculated; reject the invalid expressions with appropriate message. The program must...
C++ OOP Provide a user-friendly way to enter expressions to be evaluated. Please add a comment...
C++ OOP Provide a user-friendly way to enter expressions to be evaluated. Please add a comment explaining each step of your program. Make a program to evaluate infix arithmetic expressions containing integer operands and the operators + (addition), - (subtraction), * (multiplication), / (division) and pairs of parentheses, properly nested. Use the following two-stack algorithm (by E. W. Dijkstra): If the next token in the expression is an integer, push the integer onto the value stack. If the next token...
I need to write an interpreter for arithmetic expressions in Python. This program receives an input...
I need to write an interpreter for arithmetic expressions in Python. This program receives an input string with an arithmetic expression and does: 1. prints a ">>>" as if it was a terminal 2. lets us allocate a variable to a a numeric value (as "a = 3") then it stores {'a':3} to a dictionary memory 3. whenever it receives an expression or input, transform it to postfix notation and print it (even when allocating variables) 4. it is able...
USING C++: Consider the precedence levels of the relational, logical, and arithmetic operators of the PySub...
USING C++: Consider the precedence levels of the relational, logical, and arithmetic operators of the PySub language to be as follows (NOTE: 5 has highest precedence and 0 lowest): 5 *, /, % 4 +, - 3 <, <=, >, >=, !=, == 2 not 1 and 0 or 1.  Infix-Postfix Conversion and Evaluation with Logical and Relational operators – Convert the following infix expression to a postfix expression and evaluate the result (assume that true=1 and false=0). Provide both the...
In assignment 1 you had used the data structure called Stack to evaluate arithmetic expressions by...
In assignment 1 you had used the data structure called Stack to evaluate arithmetic expressions by first converting the given infixed expressions to postfixed expressions, and then evaluated the post fixed expression. Repeat the exercise for this assignment (assignment 2) by using the data structure called Binary Trees. Your output must display the original expression, the postfixed expression representing the Binary tree, and the evaluated result. Please bear in mind that a given expression could result in one of the...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT