Question

In: Computer Science

Arithmetic Expression Evaluation Write a program that reads an infix expression (that contains only A, B...

Arithmetic Expression Evaluation
Write a program that reads an infix expression (that contains only A, B and/or C as operands) from
the user and prints out the value of the expression as an output.
Implement the following methods:

o String infixToPostfix(String expr)
Converts the given infix expression expr and returns the corresponding postfix notation
of expr.
o Integer evaluatePostfixExpr(String expr)
Evaluates and returns the value of the given postfix expression expr.

Sample Input/Output #1
Enter your arithmetic expression: A+B-C*A
Enter the value of A: 5
Enter the value of B: 10
Enter the value of C: 2
The postfix expression is AB+CA*-
The above expression evaluates to 5.
Sample Input/Output #2
Enter your arithmetic expression: A+BC
Enter the value of A: 5
Enter the value of B: 10
Enter the value of C: 2
The above expression is invalid and can't be evaluated.


Solutions

Expert Solution

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

//Function to return precedence of operators 
int prec(char c) 
{ 
        if(c == '^') 
        return 3; 
        else if(c == '*' || c == '/') 
        return 2; 
        else if(c == '+' || c == '-') 
        return 1; 
        else
        return -1; 
} 

string infixToPostfix(string s) 
{ 
        stack<char> st; 
        st.push('N'); 
        int l = s.length(); 
        string ns; 
        for(int i = 0; i < l; i++) 
        { 
                if(s[i] >= 'A' && s[i] <= 'C')
                ns+=s[i]; 
                else if(s[i] == '(') 
                st.push('('); 
                else if(s[i] == ')') 
                { 
                        while(st.top() != 'N' && st.top() != '(') 
                        { 
                                char c = st.top(); 
                                st.pop(); 
                        ns += c; 
                        } 
                        if(st.top() == '(') 
                        { 
                                char c = st.top(); 
                                st.pop(); 
                        } 
                } 
                else{ 
                        while(st.top() != 'N' && prec(s[i]) <= prec(st.top())) 
                        { 
                                char c = st.top(); 
                                st.pop(); 
                                ns += c; 
                        } 
                        st.push(s[i]); 
                } 
        } 
        while(st.top() != 'N') 
        { 
                char c = st.top(); 
                st.pop(); 
                ns += c; 
        } 
        return ns;
} 
int operation(int a, int b, char op) {
   if(op == '+')
      return b+a;
   else if(op == '-')
      return b-a;
   else if(op == '*')
      return b*a;
   else if(op == '/')
      return b/a;
   else if(op == '^')
      return pow(b,a); //find b^a
   else
      return INT_MIN; //return negative infinity
}
int evaluatePostfixExpr(string postfix,int Aval,int Bval,int Cval) {
   int a, b;
   stack<int> stk;
   string::iterator it;
   for(it=postfix.begin(); it!=postfix.end(); it++) {
      if((*it) == '+'|| (*it) == '-'|| (*it) == '*'|| (*it) == '/' || (*it) == '^') 
      {
         a = stk.top();
         stk.pop();
         b = stk.top();
         stk.pop();
         stk.push(operation(a, b, *it));
      }
      else if((*it)>='A' && (*it)<='C') {
          {
              if((*it)=='A')
              stk.push(Aval);
              else if((*it)=='B')
              stk.push(Bval);
              else
              stk.push(Cval);
          }
      }
   }
   return stk.top();
}
bool isvalidpostfix(string postfix)
{
    stack<int>myStack;
    for(int i = 0; postfix[i] != '\0'; i++)
    {
         if(postfix[i] != '+' && postfix[i] != '-' && postfix[i] != '/' && postfix[i] != '*')
         myStack.push(postfix[i]);
         else        
         {                           
             if(myStack.size() >= 2)
                {
                    myStack.pop();
                    myStack.pop();
                }
             else
             {
                 return 1;
             }
         }
    }
    return 0;
}
int main() 
{ 
        string exp;
        int aval,bval,cval;
        cout<<"Enter your arithmetic expression: ";
        cin>>exp;
        cout<<"NOW ENTER VALUES OF VARIABLES PRESENT IN EQUATION AND IF NOT PRESENT THEN ENTER ZERO\n";
        cout<<"Enter the value of A: ";
        cin>>aval;
        cout<<"\nEnter the value of B: ";
        cin>>bval;
        cout<<"\nEnter the value of C: ";
        cin>>cval;
        string postfix=infixToPostfix(exp);
        if(isvalidpostfix(postfix)==0)
        cout<<"\nThe above expression is invalid and can't be evaluated.";
        else
        {
            cout<<"\nThe postfix expression is "<<postfix;
            cout<<"\nThe above expression evaluates to "<<evaluatePostfixExpr(postfix,aval,bval,cval);
        }
        return 0; 
}

Related Solutions

Write a program that performs the following two tasks: Reads an arithmetic expression in an infix...
Write a program that performs the following two tasks: Reads an arithmetic expression in an infix form, stores it in a queue (infix queue) and converts it to a postfix form (saved in a postfix queue). Evaluates the postfix expression. Use the algorithms described in class/ lecture notes. Use linked lists to implement the Queue and Stack ADTs. Using Java built-in classes will result in 0 points. You must use your own Stack and Queue classes (my code is a...
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.
Write a program that performs the following two tasks in java Reads an arithmetic expression in...
Write a program that performs the following two tasks in java Reads an arithmetic expression in an infix form, stores it in a queue (infix queue) and converts it to a postfix form (saved in a postfix queue). Evaluates the postfix expression. Use linked lists to implement the Queue and Stack ADTs. DO NOT USE BUILT IN JAVA CLASSES
Write a program that takes an infix expression as input and produces a postfix expression. The...
Write a program that takes an infix expression as input and produces a postfix expression. The infix and postfix expressions are in the form of vectors of strings. We will test with a main method that takes a file name as input from the command line. We will test your implementation using printPostFix() method.   There are sample input and output files in this folder. You may edit the header file. Example 1 infix expression = apple + banana * cat...
In Java, write class InfixToPostfixConverter co convert an ordinary infix arithmetic expression (assume a valid expression...
In Java, write class InfixToPostfixConverter co convert an ordinary infix arithmetic expression (assume a valid expression is entered) with single-digit integers (to make things easier) such as (6 + 2) • 5 - 8 / 4 to a postfix expression. The postfix version (no parentheses are needed) of this infix expression is 6 2 + 5 * 8 4 / - The program should read the expression into StringBuilder or String infix and use the Stack and Stack Interface class...
Question 1: Given the infix arithmetic expression as follows: Exp = Z * ((B + C...
Question 1: Given the infix arithmetic expression as follows: Exp = Z * ((B + C * D) / S + F)             Where the values of the variables are:                         Z = 3, B = 6, C = 2, D = 5, S = 4 , F = 21             Evaluate the expression using a stack. Shows the logical representation of the evaluation process. ..............................................................................
Write a C++ program that converts an infix expression, which includes (, ), +, -, *,...
Write a C++ program that converts an infix expression, which includes (, ), +, -, *, and / operations to postfix notation. The program should allow the user to enter an infix expression using lower case characters, then it will display the result of conversion on the screen. (Note: Use the STL stack class to accomplish the solution.).
Using java.util.Stack and java.util.StringTokenizer to write a program that converts an infix expression to a postfix...
Using java.util.Stack and java.util.StringTokenizer to write a program that converts an infix expression to a postfix expression using data from infix.dat. Make sure your program can handle negative number. If the input expression can’t be converted, display error message.(1.5 points) (Should remove parentheses) infix.dat 5 * 6 + -10 3 - 2 + 4 7 ( 3 * 4 - (2 + 5)) * 4 / 2 10 + 6 * 11 -(3 * 2 + 14) / 2 2...
An arithmetic expression can be represented in three different formats: infix, prefix, and postfix. In the...
An arithmetic expression can be represented in three different formats: infix, prefix, and postfix. In the infix notation, the operator comes between two operands. In the postfix notation, the operator comes after its two operands. For example, an expression a/b can be transformed to ab/. The following are some examples of the postfix expressions: 2+6*4 Its postfix notation is 2 6 4 * + 2-3+5/4*9-1 Its postfix expression is 2 3 – 5 4 / 9 * + 1 -...
: In this assignment you will write a C++ program that evaluates an arithmetic expression (represented...
: In this assignment you will write a C++ program that evaluates an arithmetic expression (represented with an infix notation), then outputs this expression in prefix form and also outputs the result of the calculation. The program will first convert the input infix expression to a prefix expression (using the Stack ADT) and then calculate the result (again, using the Stack ADT). The details are provided in the following sections.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT