Sunday, 2 September 2012

Postfix evaluation


#include<iostream.h>
#include<conio.h>
#include<ctype.h>
#include<stdio.h>

class postfix
{
private:
    char a[10],stack[10];
    int i,j,k,value;
public:
    postfix();
    void input();
    void display();
};

postfix::postfix()
{
    k=0;
    value=0;
}
void postfix::input()
{
    cout<<"Enter the expresion : "<<endl;
    for(i=0;i<9;i++)
        cin>>a[i];
    a[9]=')';
    i=0;
    j=-1;
    while(a[i]!=')')
    {
       if(isdigit(a[i]))
       {
          j++;
          stack[j]=a[i]-48;
       }
       else
       {
       k=j-1;
       switch(a[i])
       {
           case '+': value=stack[k]+stack[j];
             j=j-2;
             break;
           case '-': value=stack[k]-stack[j];
             j=j-2;
             break;
           case '*': value=stack[k]*stack[j];
             j=j-2;
             break;
           case '/': value=stack[k]/stack[j];
             j=j-2;
             break;
           }
           j++;
           stack[j]=value;
       }
       i++;
    }
}

void postfix::display()
{
    cout<<"The given Expression is : ";
    for(i=0;i<9;i++)
    cout<<a[i]<<" ";
    cout<<endl
        <<"The value of the expression is : "<<value;
}

void main()
{
    postfix p;
    clrscr();
    p.input();
    p.display();
    getch();
}

No comments:

Post a Comment