Header Ads Widget

C Program to convert Intfix expression to postfix expression.


#include<stdio.h>
#include<string.h>
#define max 50
char stack[max];
int top=-1;
void push(char element)
{
if(top==max-1)
printf("Overflow");
else
{
top+=1;
stack[top]=element;
}
}
char pop()
{
char element;
if(top==-1)
return -1;
else
{
element=stack[top];
top-=1;
return element;
}
}

int main()
{
char intfix[50],ch,item,postfix[50];
int x,length,j=0,i;
printf("Enter expression ");
scanf("%s",intfix);
length=strlen(intfix);
intfix[length]=')';
intfix[length+1]='\0';
push('(');
for( i=0;intfix[i]!='\0';i++)
{
ch=intfix[i];
x=intfix[i];
if(ch=='(')
push(ch);
if(ch=='+')
{
if(stack[top]=='-'||stack[top]=='*'||stack[top]=='/'||stack[top]=='^')
{
while(stack[top]!='(')
{
item=pop();
postfix[j]=item;
j++;
}
}
push('+');
}
if(ch=='-')
{
if(stack[top]=='+'||stack[top]=='*'||stack[top]=='/'||stack[top]=='^')
{
while(stack[top]!='(')
{
item=pop();
postfix[j]=item;
j++;
}
}
push('-');
}
if(ch=='*')
{
if(stack[top]=='*'||stack[top]=='/'||stack[top]=='^')
{
while(stack[top]!='('&&stack[top]!='+'&&stack[top]!='-')
{
item=pop();
postfix[j]=item;
j++;
}
}
push('*');
}
if(ch=='/')
{
if(stack[top]=='*'||stack[top]=='/'||stack[top]=='^')
{
while(stack[top]!='('&&stack[top]!='+'&&stack[top]!='-')
{
item=pop();
postfix[j]=item;
j++;
}
}
push('/');
}
if(ch=='^')
{
push('^');
}
if(ch==')')
{
while(stack[top]!='(')
{
item=pop();
postfix[j]=item;
j++;
}
item=pop();
}
if(x>=65&&x<=90)
{
postfix[j]=ch;
j++;
}
}
postfix[j]='\0';
printf("\n%s",postfix);
return 0;
}

 




Post a Comment

1 Comments