Sunday 6 October 2013

C++ program to evaluate postfix expression

#include<iostream>
using namespace std;
#include<conio.h>
#include<string.h>
template<class T>
class evaluation
{
      private:
              T postfix[20];
              int stack[20],top;
      public:
             evaluation()
             {
                         top=-1;
             }
             void getpostfixexpr();
             void calculate();
             void display();
};
template<class T>
void evaluation<T>::getpostfixexpr()
{
     cout<<"\n enter the postfix expression :";
     cin>>postfix;
}
template<class T>
void evaluation<T>::display()
{
     cout<<"\n the calculate value is :"<<stack[top];
}
template<class T>
void evaluation<T>::calculate()
{
     int l=strlen(postfix);
     int k=l;
     for(int i=0;i<k;i++)
     {
             int x;
             if((postfix[i]>='a'&&postfix[i]<='z')||(postfix[i]>='A'&&postfix[i]<='Z'))
             {
                          cout<<"\n enter the value of "<<postfix[i]<<":";
                          cin>>x;
                          stack[++top]=x;
             }
             else
             {
                 int a=stack[top];
                 int b=stack[top-1];
                 switch(postfix[i])
                 {
                                   case '+':
                                        stack[top-1]=b+a;
                                        top--;
                                        break;
                                   case '-':
                                        stack[top-1]=b-a;
                                        top--;
                                        break;
                                   case '*':
                                        stack[top-1]=b*a;
                                        top--;
                                        break;
                                   case '/':
                                        stack[top-1]=b/a;
                                        top--;
                                        break;
                 }
             }
     }
}
int main()
{
    evaluation<char> e;
    e.getpostfixexpr();
    e.calculate();
    e.display();
    _getch();
    return 0;
}

No comments:

Post a Comment