Wednesday, September 24, 2008

program converts an infix string to postfix expression

program converts an infix string to postfix expression....i have kept no place for input..please change the char a[] in void main() and it will act as the input.....if any new symbols are to be added please add them to op[] and also its corresponding order of precedence in prec[]




















#include
#include
#include
#include
int top=0,opn=5;
char op[]={'^','*','/','+','-'};
int prec[]={1,2,2,3,3};
char pop(char s[]);
int isoperand(char);
void push(char s[],char);
int prcdnc(char,char);

void main()
{

char a[]="a+(b*c-(d/e^f)*g)*h",stk[50],c[50],temp,symb;
int l,i=0,r=0;
l=strlen(a);
a[l]=')';
a[l+1]=NULL;
stk[0]='(';
while(a[r]!=NULL)
{
symb=a[r];
if(isoperand(symb))
{
c[i]=symb;
i++;
}
else if(symb==')')
{
while(1)
{
temp=pop(stk);
if(temp=='(')
break;
else
{
c[i]=temp;
i++;
}
}
}
else if(symb=='(')
push(stk,symb);
else
{
while(1)
{
if(stk[top]=='(')
{
push(stk,symb);
break;
}
else if(prcdnc(stk[top],symb))
{
c[i]=pop(stk);
i++;
}
else
{ push(stk,symb);
break;
}
}
}
r++;
}
c[i]=NULL;
printf("\nThe post fix expression is= %s",c);
getch();
}

int prcdnc(char a,char b)
{
int num1,num2,i;
for(i=0;i
{
if(op[i]==a)

num1=prec[i];

if(op[i]==b)
num2=prec[i];
}
if(num2<=num1) return 0; else return 1; } void push(char s[],char a) { top=top+1; s[top]=a; } char pop(char s[]) { char val; val= s[top]; top=top-1; return val; } int isoperand(char a) { int i; if(a=='(' || a==')') return 0; for(i=0;i
{
if(op[i]==a)
return 0;
}
return 1;
}

No comments:

Post a Comment

Thanks to given comments.......

My Blog List