Tuesday, March 26, 2013

Infix to postfix conversion


Infix to postfix

#include
#include
#include
int isp(char);
int icp(char);
void main()
{
char s[50],q[50],p[50],ch,item;
int i,n,len,top=-1,ic,is,j=0;
clrscr();
top=top+1;
s[top]='$';
printf("\nEnter expression:");
gets(q);
len=strlen(q);

for(i=0;i
{
ch=q[i];
if(ch=='(')
{
top=top+1;
s[top]=ch;       //push '(' to stack
}
else if(ch=='+'||ch=='-'||ch=='*'||ch=='/'||ch=='^')    /* on operator*/
{
 is=isp(s[top]);
 ic=icp(ch);

  if(ic
  {
   item=s[i];    //pop from stack on isp>icp
   top=top-1;
   p[i]=item;
  }
 top=top+1;
 s[top]=ch;       //push operator to stack
}

else if(ch==')') /* on ')' para */
{
 while(s[top]!='(')
 {
 p[j]=s[top];
 j++;
 top=top-1;
 }
 top=top-1;
}

else            /* on operand */
{
 p[j]=ch;
 j++;
}
}

printf("Postfix expression is:\n");
for(i=0;i
{
printf("%c",p[i]);
}
getch();
}
int isp(char ch)
{
switch(ch)
{
case '+':return(2);

case '-':return(2);

case '*':return(4);

case '/':return(4);

case '^':return(5);

case '(':return(0);

case ')':return(0);
default:return(0);
}
}
int icp(char ch)
{
switch(ch)
{
case '+':return(1);
case '-':return(1);
case '*':return(3);
case '/':return(3);
case '^':return(6);
case '(':return(9);
case ')':return(0);
default:return(0);
}
}

No comments: