Program to convert infix expression to postfix and evaluate the postfix expression
PROGRAM
#include<iostream>
#include<cmath>
#include<cstring>
#include<cstdio>
#include<cctype>
Using
namespace std;
class
infix
{
char
in[20],post[20],stack[20];
int
top,s[50],cp,co;
public:
infix()
{
top=-1;
co=cp=0;
}
void read();
void errorcheck();
void display();
void convert();
int evaluate();
int prior(char c);
void push(char c);
void push1(int val);
int pop1();
char pop();
};
void
infix::read()
{
cout<<"Enter
the infix expression:";
gets(in);
}
void
infix::display()
{
cout<<"The
infix expression is ";
puts(in);
cout<<"The
postfix expression is ";
puts(post);
}
void
infix::errorcheck()
{
int
i=0;
do
{
if(isalpha(in[i]))
co++;
else
if(in[i]=='(')
cp++;
else
if(in[i]==')')
cp--;
else
co--;
i++;
}while(in[i]!='\0');
if((cp!=0)||(co!=1))
cout<<"\nInvalid
expression";
}
void
infix::push(char c)
{
top=top+1;
stack[top]=c;
}
void
infix::push1(int val)
{
top=top+1;
s[top]=val;
}
int
infix::pop1()
{
int
temp;
temp=s[top];
top=top-1;
return
temp;
}
char
infix::pop()
{
char
t;
t=stack[top];
top=top-1;
return
t;
}
int
infix::prior(char c)
{
switch(c)
{
case
'+':
case
'-':return 1;
case
'*':
case
'/':return 2;
case
'^':return 3;
}
}
void
infix::convert()
{
int
i=0,k=0;
char
c;
do
{
if(isalpha(in[i]))
post[k++]=in[i];
else if(in[i]=='(')
push(in[i]);
else if(in[i]==')')
{
while(top>=0)
{
c=pop();
if(c!='(')
post[k++]=c;
else
break;
}
}
else if(!isalpha(in[i]))
{
if(top==-1)
push(in[i]);
else
{
while(top>=0)
{
c=pop();
if(c=='(')
{
push(c);
break;
}
else
{
if(prior(c)<prior(in[i]))
{
push(c);
break;
}
else
post[k++]=c;
}//else
}//while
push(in[i]);
}//else
}
i++;
}while(in[i]!='\0');
while(top>=0)
post[k++]=pop();
post[k]='\0';
}
int infix::evaluate()
{
top=-1;
int
i=0,val;
do
{
if(isalpha(post[i]))
{
cout<<"Enter the value for
"<<post[i];
cin>>val;
push1(val);
}
else
{
int op1,op2;
op1=pop1();
op2=pop1();
switch(post[i])
{
case '+':val=op1+op2;
break;
case '-':val=op1-op2;
break;
case '*':val=op1*op2;
break;
case '/':val=op1/op2;
break;
case '^':val=pow(op1,op2);
break;
}
push1(val);
}i++;
}while(post[i]!='\0');
return pop1();
}
void main()
{
infix
p;
int v;
p.read();
p.errorcheck();
p.convert();
p.display();
v=p.evaluate();
cout<<"The result is
"<<v;
getch();
}
OUTPUT
Enter
the infix expression:a+b*c
The
infix expression is a+b*c
The
postfix expression is abc*+
Enter
the value for a 3
Enter
the value for a 5
Enter
the value for a 1
The
result is 8