Program to convert an expression from infix notation into postfix.
#include<iostream.h>
#include<conio.h>
#include<stdio.h>
#include<string.h>
#include<ctype.h>
void main()
{
char exp[100],inf[100],op[50];
int len,j=0,k=-1;
cout<<"Enter the equation : \n";
gets(exp);
len=strlen(exp);
for(int i=0;i<len;i++)
{
if(isalnum(exp[i]))
{
inf[j]=exp[i];
j++;
}
else if(!isdigit(exp[i])&&exp[i]!=')')
{
if(exp[i]=='+' || exp[i]=='-')
{
while(k!=-1 && op[k]!='(')
{
inf[j]=op[k];
j++;
k--;
}
if(op[k]=='(')
{
k--;
}
}
if(exp[i]=='*'&&op[k]=='/' || exp[i]=='/'&&op[k]=='*')
{
inf[j]=op[k];
j++;
k--;
}
k++;
op[k]=exp[i];
}
else if(exp[i]==')')
{
while(op[k]!='(')
{
inf[j]=op[k];
j++;
k--;
}
k--;
}
}
inf[j]='\0';
cout<<"PostFix Expression is : \t";
cout<<inf;
getch();
}
No comments:
Post a Comment