Monday, May 24, 2010

Can anyone give me a c-code for evaluating an infix expression using stack without converting it to postfix?

/*Program to evaluate Conversion of INFIX to POSTFIX*/


#include%26lt;iostream.h%26gt;


#include%26lt;conio.h%26gt;


#include%26lt;stdio.h%26gt;


#include%26lt;string.h%26gt;


#include%26lt;stdlib.h%26gt;


void main()


{


char in[30],post[30],stack[30],st[10];


int ch,j=0,top=0,len,temp,var,var1,stack1[30...


clrscr();


cout%26lt;%26lt;"Enter a notation in infix form";


gets(in);


stack[0]='(';


len=strlen(in);


in[len]=')';


for(int i=0;i%26lt;=len;i++)


{


ch=in[i];


if(ch==42||ch==43||ch==45||ch==47)


{


if(in[i]=='*'||in[i]=='/')


{


ch=100;


}


if(in[i]=='+'||in[i]=='-')


{


ch=101;


}


if(ch%26gt;=stack[top])


{


top++;


stack[top]=in[i];


}


if(ch%26lt;stack[top])


{


if(stack[top]!=40)


{


post[j]=stack[top];


stack[top]=in[i];


j++;


}


}


}


if(ch%26gt;=48%26amp;%26amp;ch%26lt;=57)


{


post[j]=in[i];


j++;


}


if(ch==40)


{


top++;


stack[top]='(';


}


if(ch==41)


{


while(1)


{


if(int(stack[top])==40)


{


break;


}


else


{


post[j]=stack[top];


top--;


j++;


}


}


top--;


}


}


cout%26lt;%26lt;"\nPost Fix notation is";


for(i=0;i%26lt;j;i++)


cout%26lt;%26lt;post[i];


top=0;


for(i=0;i%26lt;j;i++)


{


ch=post[i];


if(ch%26gt;=48%26amp;%26amp;ch%26lt;=57)


{


top++;


stack1[top]=ch-48;


}


if(ch==42||ch==43||ch==45||ch==47)


{


var=stack1[top];


top--;


var1=stack1[top];


top--;


switch(ch)


{


case 42:


res=var1*var;


break;


case 43:


res=var1+var;


break;


case 45:


res=var1-var;


break;


case 47:


res=var1/var;


break;


}


top++;


stack1[top]=res;


}


}


cout%26lt;%26lt;"\nEvaluation of PostFix Expression is";


cout%26lt;%26lt;stack1[top];


getch();


}


This is the code.Gud luck.


No comments:

Post a Comment