Friday 23 September 2011

Pstfix Evalution program


#include<iostream>
#include<cstdlib>
#include<cmath>
using namespace std;
class posteval
{
  char postfix[30];
  int stack[30];
  int top;
  public:
  posteval()
    {
     top=-1;
    }
  void push(int);
  int pop();
  void eval();
};
void posteval::push(int ele)
{
  stack[++top]=ele;
}
int posteval::pop()
{
 return stack[top--];
}
void posteval::eval()
{
 int r,v1,v2;
 cout<<"Enter the postfix expression";
 cin>>postfix;
 for(int i=0;postfix[i]!='\0';i++)
  {
    int f=0;
    switch(postfix[i])
      {
        case '+':
          {
             v2=pop();
             v1=pop();
             r=v1+v2;
          }
          break;
        case '-':
          {
            v2=pop();
            v1=pop();
             r=v1-v2;
          }
          break;
        case '*':
          {
            v2=pop();
            v1=pop();
             r=v1*v2;
          }
          break;
        case '/':
          {
            v2=pop();
            v1=pop();
             r=v1/v2;
          }
         break;
        case '^':
          {
            v2=pop();
            v1=pop();
             r=pow(v1,v2);
          }
          break;
        default:
          {
             push(postfix[i]-48);
             f=1;
          }

     }
     if(f==0)
           push(r);
   }
   cout<<"\nResult of postfix evaluation is "<<stack[top]<<"\n";
}
int main()
{
  posteval ob;
  ob.eval();
}

No comments:

Post a Comment