PROGRAM FROM INFIX TO POSTFIX EXPRESSION IN C++

INFIX TO POSTFIX EXPRESSION

Conventional notation is called infix notation. The arithmetic operators appears between two operands. Parentheses are required to specify the order of the operations. For example: a + (b * c).

Post fix notation (also, known as reverse Polish notation) eliminates the need for parentheses. There are no precedence rules to learn, and parenthese are never needed. Because of this simplicity, some popular hand-held calculators use postfix notation to avoid the complications of multiple sets of parentheses. The operator is placed directly after the two operands it needs to apply. For example: a b c * +

This short example makes the move from infix to postfix intuitive. We tried to solve the same using the C++ programming code and the same is complete working coded and output is also shown below. 

Use it for your understanding purpose and share it with your friends. 



#include<iostream.h>
#include<conio.h>
#include<string.h>

int heavy(char);
void main()
{
char *ch,t[50],stack[10],postfix[10];
int p=0,p1=0,top=-1,post=-1;
clrscr();
cout<<"\n=====================================================================";
cout<<"\n.............CONVERSION OF INFIX TO POSTFIX EXPRESSION...............";
cout<<"\n=====================================================================\n";
cout<<"Enter Infix Expression to convert (such as: a+b-c/d*p^q):\n\n";
cin>>ch;
strcpy(t,ch);
for(int i=0;ch[i]!='\0';i++)
{
if(ch[i]>=65 && ch[i]<=90 || ch[i]>=97 && ch[i]<=122)
{
post++;
postfix[post]=ch[i];
}
else if(ch[i]=='/'||ch[i]=='*'||ch[i]=='+'||ch[i]=='-')
{
if(top<0)
{
top++;
stack[top]=ch[i];
}
else
{
p=heavy(stack[top]);
p1=heavy(ch[i]);
if(p>p1)
{
post++;
postfix[post]=stack[top];
stack[top]=ch[i];
}
else
{
top++;
stack[top]=ch[i];
}
}
}
}

for(i=top;i>=0;i--)
{
post++;
postfix[post]=stack[i];
}

cout<<"\nInfix Expression : \n"<<t<<"\n\nPostifix Expression : \n";
for(i=0;i<=post;i++)
{
cout<<postfix[i];
}
cout<<"\n=====================================================================\n";
getch();
}

int heavy(char ch)
{
int temp;
if(ch=='/')
temp=4;
else if(ch=='*')
temp=3;
else if(ch=='+')
temp=2;
else if(ch=='-')
temp=1;
return temp;
}




No comments

Post your comments

Powered by Blogger.