Sunday, December 12, 2010

Infix Expression Evaluation Using Expression Tree

//program to Evaluate Infix Expression Using Expression Tree
#include
#include
#include
#include
#include

class infix
{
typedef struct stack
{
char c;
struct stack *next;
}stack;
stack *top;
char ch,post[20],t,f;
int i,j,val[10],temp;

public:
infix()
{
top=NULL;
i=j=-1;
}

void read();
int precidence(char);
void push(char);
char pop();
};
void infix::read()
{
system("clear");
push('(');
cout<<"-----INFIX EXPRESSION EVALUATION-------\n";
cout<<"\nEnter the Infix expression : ";
do
{
ch=getchar();
if(ch=='\n')
{
t=ch;
ch=')';
}
if(ch=='(')
push(ch);
else if((ch>='a' && ch<='z')||(ch>='A' && ch<='Z'))
post[++i]=ch;
else if(ch==')')
{
ch=pop();
while(ch!='(')
{
post[++i]=ch;
ch=pop();
}
}
else
{
f=pop();
if(precidence(ch)>precidence(f))
{
push(f);
push(ch);
}
else
{
post[++i]=f;
push(ch);
}
}
}while(t!='\n');
post[++i]='\0';
cout<<"\nPostfix Expression : ";
for(i=0;post[i]!='\0';++i)
cout< cout<<"\n";
for(i=0;post[i]!='\0';++i)
{
ch=post[i];
switch(ch)
{
case '*': val[j-1]*=val[j--];
break;
case '/': val[j-1]/=val[j--];
break;
case '+': val[j-1]+=val[j--];
break;
case '-': val[j-1]-=val[j--];
break;
case '^': temp=pow(val[j-1],val[j]);
val[--j]=temp;
break;
default: cout<<"Enter the value of "< cin>>val[++j];
break;
}
}
cout<<"\nResult after evaluation:"<}
int infix::precidence(char c)
{
switch(c)
{
case '(': return 0;
case '+':
case '-': return 1;
case '/':
case '%': return 2;
case '^':
case '$': return 3;

}
return 0;
}
void infix::push(char ch)
{
stack *p;
p=new stack;
p->c=ch;
p->next=top;
top=p;
}
char infix::pop()
{
stack *temp=top;
char ch=top->c;
top=top->next;
delete(temp);
return ch;
}
void main()
{
infix in;
in.read();

getch();
}

OUTPUT


-----INFIX EXPRESSION EVALUATION-------

Enter the Infix expression : a*b+c/d-e^f

Postfix Expression : ab*cd/ef^-+

Enter the value of 'a' :5
Enter the value of 'b' :6
Enter the value of 'c' :8
Enter the value of 'd' :4
Enter the value of 'e' :2
Enter the value of 'f' :3

Result after evaluation: 24

No comments:

Post a Comment