Program to show infix to Postfix in C Programming



#include
#include
#include
#include
#include
class ds
{
private:
int stack[25];
char infix[25];
public:
int isp(char);
int icp(char);
void convert();
void getdata();
};
void ds::getdata()
{
cout< cin>>infix;
}

int ds::isp(char ch)
{
if(ch=='+' ||ch== '-')
return(2);
if(ch=='*' ||ch== '/')
return(4);
if(ch=='^')
return(5);
if(ch>=65 && ch<=90)
return(8);
if(ch>=97 && ch<=122)
return(8);
if(ch=='(')
return(0);
}
int ds::icp(char ch)
{
if(ch=='+' ||ch== '-')
return(1);
if(ch=='*' ||ch== '/')
return(3);
if(ch=='^')
return(5);
if(ch>=65 && ch<=90)
return(7);
if(ch>=97 && ch<=122)
return(7);
if(ch=='(')
return(9);
if(ch=='(')
return(0);
}

void ds::convert()
{
char item,x;
int top=0;
top=top+1;
stack[top]='(';
int i=1;
while(top>0)
{
item=infix[i];
//if(i<=strlen(infix));
i++;
x=stack[top];
top--;
if(item>=65&&item<=90)
{
top++;
stack[top]=x;
cout< }
else if(item>=97&&item<=122)
{
top++;
stack[top]=x;
cout< }
else if(item==')')
{
while(x!='(')
{
cout< x=stack[top];
top--;
}
}
else if(isp(x)>=icp(item))
{
while((isp(x))>=icp(item))
{
cout< x=stack[top];
top--;
}
top++;
stack[top]=x;
top++;
stack[top]=item;
}
else if(isp(x) {
top++;
stack[top]=x;
top++;
stack[top]=item;
}
else
cout<<"invalid expression";
}
getch();
}
void main()
{
clrscr();
ds d;
d.getdata();
cout<<"Postfix expression is:";
d.convert();
}


1 comment: