Sunday, September 25, 2016

Transforming INFIX to POSTFIX Expression

Tags

Program to Convert An Infix Expression To Postfix Expression:


#include<stdio.h>
#include<ctype.h> //for isalnum function
char stack[50];
int top=-1;
void push(char x)
{
if(top==49)
{printf("Overflow");
}
else{

stack[++top]=x;
}
}
char pop()
{ if(top==-1)
{
return -1;
}
else{

return stack[top--];
}
}
int priority(char x)
{
if(x=='(')
return 0;
else if(x=='+'||x=='-')
 return 1;
 else if(x=='*'||x=='/')
 return 2;
}
main()
{
char infix[50];
char x,*e;  //pointer to access each character
printf("Enter The Expression  ");
scanf("%s",infix);
e=infix;
while(*e!='\0')
{
if(*e=='(')
{
push(*e);
}
else if(isalnum(*e))
{
printf("%c",*e);
}
else if(*e==')')
{
while((x=pop())!='(')
printf("%c",x);
}
else
{
while(priority(stack[top])>=priority(*e))
printf("%c",pop());
push(*e);
}
e++;}
while(top!=-1)
printf("%c",pop());
}

Output: