C program to convert infix to postfix expression
Program:
#include <stdio.h>
#include <string.h>
int push(char item,char s[],int top)
{
top=top+1;
s[top]=item;
return top;
}
char pop(char s[],int *top)
{
char k;
k=s[*top];
*top=*top-1;
return k;
}
int priority(char ch)
{
if (ch=='^')
return 3;
else if ((ch=='*') || (ch=='/'))
return 2;
else if ((ch=='+') || (ch=='-'))
return 1;
}
void display(char post[])
{
puts(post);
}
int main()
{
char inf[100],post[100],stack[100],y,x,ch;
int i=0,j=0,l,top=-1;
printf("\nEnter the infix expression: ");
gets(inf);
while((ch=inf[i++])!='\0')
{
if ((ch>='A' && ch<='Z') || (ch>='a' && ch<='z'))
{
post[j]=ch;
j++;
}
else if (ch=='(')
top=push(ch,stack,top);
else if (ch==')')
{
y=pop(stack,&top);
while (y!='(')
{
post[j]=y;
j++;
y=pop(stack,&top);
}
}
else
{
if((top==-1)||(stack[top]=='(')||(priority(stack[top])<priority(ch)))
{
top=push(ch,stack,top);
}
else
{
while((priority(stack[top])>=priority(ch))&&(top!=-1)&&(stack[top]!='('))
{
x=pop(stack,&top);
post[j]=x;
j++;
}
top=push(ch,stack,top);
}
}
}
while(top>-1)
{
x=pop(stack,&top);
post[j]=x;
j++;
}
display(post);
}
Output:
Enter the infix expression: ((a/b)+(c*d))/e
ab/cd*+e/
#include <stdio.h>
#include <string.h>
int push(char item,char s[],int top)
{
top=top+1;
s[top]=item;
return top;
}
char pop(char s[],int *top)
{
char k;
k=s[*top];
*top=*top-1;
return k;
}
int priority(char ch)
{
if (ch=='^')
return 3;
else if ((ch=='*') || (ch=='/'))
return 2;
else if ((ch=='+') || (ch=='-'))
return 1;
}
void display(char post[])
{
puts(post);
}
int main()
{
char inf[100],post[100],stack[100],y,x,ch;
int i=0,j=0,l,top=-1;
printf("\nEnter the infix expression: ");
gets(inf);
while((ch=inf[i++])!='\0')
{
if ((ch>='A' && ch<='Z') || (ch>='a' && ch<='z'))
{
post[j]=ch;
j++;
}
else if (ch=='(')
top=push(ch,stack,top);
else if (ch==')')
{
y=pop(stack,&top);
while (y!='(')
{
post[j]=y;
j++;
y=pop(stack,&top);
}
}
else
{
if((top==-1)||(stack[top]=='(')||(priority(stack[top])<priority(ch)))
{
top=push(ch,stack,top);
}
else
{
while((priority(stack[top])>=priority(ch))&&(top!=-1)&&(stack[top]!='('))
{
x=pop(stack,&top);
post[j]=x;
j++;
}
top=push(ch,stack,top);
}
}
}
while(top>-1)
{
x=pop(stack,&top);
post[j]=x;
j++;
}
display(post);
}
Output:
Enter the infix expression: ((a/b)+(c*d))/e
ab/cd*+e/
No comments