PROGRAM TO EVALUATE POSTFIX EXPRESSIONS.

#include<iostream.h>             //HEADER FILES
#include<string.h>
#include<ctype.h>
#include<process.h>
#include<math.h>
#define SIZE 50

class stack                      //STACK DEFINITION
{
float arr[SIZE];
int top;
public:                       //FUNCTIONS OF STACK CLASS
bool isempty();
bool isfull();
void push(float);
float pop();
void display();
void convert(char *);
stack()
{
top=-1;
}
};

bool stack::isempty()             // FUNCTION DEFINITION
{
return(top==-1);
}

bool stack::isfull()
{
return(top==(SIZE-1));
}
void stack::push(float ch)               // FUNCTION DEFINATION TO INSERT AN ITEM INTO STACK
{
if(isfull())
{
cout<<"\n STACK OVERFLOW";
return;
}
arr[++top]=ch;
}
float stack::pop()                       // FUNCTION DEFINITION TO DELETE AN ITEM FORM STACK
{
if(isempty())
return('?');
return(arr[top--]);
}
void stack::display()                    // FUNCTION DEFINATION TO DESPLAY STACK(STCK ITEMS)
{
cout<<endl;
if(isempty())
{
cout<<" STACK EMPTY";
return;
}
for(int i=0;i<=top;i++)
cout<<arr[i];
}

void stack::convert(char* array)                    // FUNCTION DEFNATION TO CONVERT INTO POSTFIX
{
int i,j,l;//,index=-1;
float a,b,num,dec;
l=strlen(array);
for(i=0;i<l;i++)
{
num=0;
dec=1;
if(array[i]==' ')
continue;
if(isdigit(array[i]))
{
for(j=i;array[j]!='.'&&array[j]!=' ';j++)
num=num*10+(array[j]-48);
if(array[j]=='.')
for(j++;array[j]!=' ';j++)
{
dec/=10;
num=num+dec*(array[j]-48);
}
i=j;
push(num);
continue;
}
if((i<l)&&(!isdigit(array[i])))
if(top<1)
{
cout<<"\n SYNTAX ERROR  EXTRA OPERATOR ENCOUNTERED";
exit(0);
}
b=pop();
a=pop();
switch(array[i])
{
case '+': a+=b;
push(a);
break;
case '-': a-=b;
push(a);
break;
case '*': a*=b;
push(a);
break;
case '/': if(b==0)
{
cout<<"\n MATH ERROR  DIVISION BY ZERO ENCOUNTERED";
exit(0);
}
else
{
a/=b;
push(a);
}
break;
case '%': if(b==0)
cout<<"\n MATH ERROR  DIVISION BY ZERO ENCOUNTERED";
else
{
a=(int)a%(int)b;
push(a);
}
break;
case '$': a=pow((int)a,(int)b);
push(a);
break;
}
}
cout<<"\n result ::"<<pop()<<endl;
}

void main()
{
stack postfix;
char exp[SIZE];
cout<<"\n ENTER THE POSTFIX EXPRESSION"
<<"\n USE SPACE BETWEEN OPERATOR AND OPERANDS:\n";
cin.getline(exp,SIZE);
postfix.convert(exp);
}

Advertisements

19 thoughts on “PROGRAM TO EVALUATE POSTFIX EXPRESSIONS.

  1. Thankz andrew. Your comment motivate us a lot to add more useful things in this blog. We are adding more interesting stuff so see you soon :).

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s