57)Write a C program to convert accepted infix expression to its equivalent postfix expression.


#include<stdio.h>
#include<conio.h>
char st[100];
int top=-1;
int prec(char c)
{
switch(c)
{
case ‘(‘:
return 0;
case ‘+’:
case ‘-‘:
return 1;
case ‘*’:
case ‘/’:
case ‘%’:
return 2;
case ‘^’:
return 3;
}
return 0;
}
void push(char c)
{
top++;
st[top]=c;
}
char pop()
{
char c;
c=st[top];
top–;
return c;
}
int main()
{
int i,j,p,a,b,temp;
char ch,s1[30],s2[30];
clrscr();
printf(“\nEnter the Infix Expr”);
gets(s1);
j=0;
for(i=0;s1[i]!=”;i++)
{
switch(s1[i])
{
case ‘(‘:
case ‘+’:
case ‘-‘:
case ‘/’:
case ‘*’:
case ‘^’:
p=prec(s1[i]);
while(top!=-1 && p<=prec(st[top]))
s2[j++]=pop();
push(s1[i]);
break;
case ‘)’:
do
{
ch=pop();
if(ch!='(‘)
{
s2[j++]=ch;
}
}
while(ch!='(‘);
break;
default:
s2[j++]=s1[i];
}
}
while(top!=-1)
{
s2[j++]=pop();
}
s2[j]=”;
printf(“\nPostFix Expr %s”,s2);
// getch();
// return 0;
// }
printf(“\n\nEval of PostFix Expr is \n\n”);
j=0;
for(i=0;s2[i]!=”;i++)
{
if(s2[i]<=’9′ && s2[i]>=’0’)
push(s2[i]-48);
else
{
a=pop();
b=pop();
switch(s2[i])
{
case ‘+’:
temp=b+a;
break;
case ‘-‘:
temp=b-a;
break;
case ‘/’: temp=b/a;
break;
case ‘*’:
temp=b*a;
break;
case ‘^’:
temp=pow(b,a);
break;
case ‘%’:
temp=b%a;
break;
}
push(temp);
}
}
j=pop();
printf(“Result is %d “,j);
getch();
return;
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s