Write a class ArithmeticExpressionEvaluator that evaluates an infix arithmetic e
ID: 3863469 • Letter: W
Question
Write a class ArithmeticExpressionEvaluator that evaluates an infix arithmetic expression. Do this is two steps. first, convert the infix expression of a postfix expression: create a filter Infix ToPostfix that coverts an arithmetic expression from infix to postfix. Second, evaluate the postfix expression: write a postfix evaluator Evaluate Postfix that takes a postfix expression, evaluates it and print the value. Your program should print the infix expression, postfix expression, and the final result.Explanation / Answer
#include<iostream>
#include<string.h>
using namespace std;
class Stack
{
char a[50];
public:
int latest;
Stack()
{
latest=-1;
}
void add(char value)
{
if(latest==4)
return;
latest++;
a[latest]=value;
}
char pop()
{
if(latest==-1)
return -1;
char val=a[latest];
latest--;
return val;
}
// A utility function to return precedence of a given operator
// Higher returned value means higher precedence
int Prec(char ch)
{
switch (ch)
{
case '+':
case '-':
return 1;
case '*':
case '/':
return 2;
case '^':
return 3;
default :
return -1;
}
}
int isEmpty
{
if(latest== -1)
{
return 1;
}
else
{
return 0;
}
}
int isOperand(char ch)
{
if((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z'))
return 1;
else
return 0;
}
void display()
{
for(int i=0;i<latest;i++)
{
cout<<a[i];
}
}
};
class ArithmeticExpressionEvaluator
{
Stack s;
Stack pf; /
public :
ArithmeticExpressionEvaluator(char a[50])
{
for(int i=0; i<50 ;i++)
{
s.add(a[i]);
s.display();
}
}
void infixToPostfix() //function that converst infix to postfix
{
Stack op; //stack of operators
char p;
while(s.latest != -1)
{
p=s.pop();
while(isOperand(p)==1)
{
pf.add(p); //if the char is operator
}
while(isOperand(p)==0)
{
if(op.isEmpty()==1)
{
op.add(p);
}
else if(op.prec(p>=s.pop())
{
op.add(p);
op.add(s.pop());
}
else
{
pf.add(op.pop());
}
}
cout<<"the postfix expression is"<<pf.display(); // displaying the postfix expression
}
}
void postfixEvaluation
{
Stack eval ;
while(pf.latest != -1)
{
char l;
l=pf.pop();
if(isOperand(l)== 1)
{
eval.add(l);
}
else
{
char last1,last2;
last1=eval.pop();
last2=eval.pop();
switch(l)
{
case '+':
eval.add(last1+last2); //here last1 nd last2 are characters but in feality they must be integers
break;
case '-':
eval.add(last2-last1);
break;
case '*':
eval.add(last1*last2);
break;
case '/':
eval.add(last2/last1);
break;
}
}
}
cout<<"the evaluated value is :"<<eval.display();
}
};
main()
{
char exp[50];
cout<<"enter the expression";
cin>exp[50];
ArithmeticExpressionEvaluator ae(exp[50]);
ae.infixToPostfix();
ae.postfixEvaluation();
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.