Friday, August 31, 2012

C Program for Postfix Expression Evaluation

#include<iostream.h>
#include<process.h>
#include<string.h>
#include<stdlib.h>
#include<stdio.h>
#include<conio.h>
class stack
{
   double x[10],TOP,i,j,count,t,a,b,r;
   char exp[10][10],ch;
   public:
   void read();
   double pop();
   void push(double);
   double convert(double);
   double check(double);
   double process();
};
void stack::read()
{
  puts("Enter Expression in Postfix Form,Press E at End\n");
  count=0;
  do
  {
   count++;
   cin>>exp[count];
  }while(exp[count][0]!='E');
  puts("\n-------------------------------------------------");
}
double stack::pop()
{
  if(TOP<1)
  {
    cout<<"\nSORRY!Stack Underflow....";
    exit(0);
  }
  return(x[TOP--]);
}
void stack::push(double y)
{
  if(TOP==10)
  {
    cout<<"\nSORRY!Stack Overflow....";
    exit(0);
  }
  x[++TOP]=y;
  cout<<"\nElement in Stack.:\t";
  for(int t=1;t<=TOP;t++)
  cout<<"  "<<x[t];
}
double stack::check(double temp)
{
  if(strlen(exp[temp])>1)
  return 1;
  else
  {
    switch(exp[temp][0])
     {
      case '+':
      case '-':
      case '*':
      case '/':
      return 0;
      default:
      return 1;
     }
  }
}
double stack::convert(double temp)
{
   char *endptr;
   double l;
   l=strtod(exp[temp],&endptr);
   return l;
}
double stack::process()
{
  double t;
  TOP=0;
  int i=1;
  do
  {
   t=check(i);
   if(t==1)
   {
     t=convert(i);
     push(t);
   }
   else
   {
    a=pop();
    b=pop();
    switch(exp[i][0])
     {
      case '+':
     cout<<"\nOperator Detected.: +";
     push(a+b);
     break;
      case '-':
     cout<<"\nOperator Detected.: -";
     push(b-a);
     break;
      case '*':
     cout<<"\nOperator Detected.: *";
     push(a*b);
     break;
      case '/':
     cout<<"\nOperator Detected.: /";
     push(b/a);
     break;
      default:
     cout<<"\nSORRY!Invalid Input....";
     exit(0);
     }
   }
   i++;
  }while(exp[i][0]!='E');
  return(x[TOP]);
}
void main()
{

  char ch;
  double i,j;
  clrscr();
  stack x;
  puts("===================================================");
  cout<<"Enter Expression in POSTFIX FORM.\n";
  cout<<"Enter E at the End of Expression.\n";
  puts("===================================================");
  x.read();
  i=x.process();
  puts("\n-------------------------------------------------");
  cout<<"\t-*- Result="<<i<<"  -*-";
  puts("\n-------------------------------------------------");
  getch();
}

No comments:

Post a Comment