Search This Blog

Tuesday 27 October 2015

postfix evaluation

#include<stdio.h>
#include<conio.h>
int stack[50];
int top=-1;
void push(int);
float pop();
float eval(char[],int[]);
void main()
 {   int i=0;
    char suffix[20];
    int value[20];
    float result;
    clrscr();
    printf("\nenter a valid postfix expression");
    gets(suffix);
      while(suffix[i]!='\0')
   {
       if(isalpha(suffix[i]))
      {
         printf("\nenter the values of%c",suffix[i]);
         scanf("%d",&value[i]);
      }
         i++;
   }
     result=eval(suffix,value);
     printf("result of %s %f",suffix,result);
     getch();
 }
float eval(char suffix[],int value[])
 {
      int i=0;
      int op1,op2,res;
      char ch;
     while((suffix[i])!='\0')
  {
        ch=suffix[i];
        if(isalpha(suffix[i]))
          {
            push(value[i]);
          }
        else
          {        
             op2=pop();
             op1=pop();
             switch(ch)
              {
               case '+':push(op1+op2);
                          break;
               case '-':push(op1-op2);
                           break;
               case '*':push(op1*op2);
                           break;
               case '/':push(op1/op2);
                           break;
               case '^':push(pow(op1,op2));
                           break;
              }
           }
         i++;
   }
     res=pop();
     return(res);
 }
void push(int a)
 {
      if(top>=49)
    {   
      printf("stack overflow");
      getch();
      return;
    }
       else
     { 
       top=top+1;
       stack[top]=a;
     }
  }
     float pop()
   {
       int item;
         if(top==-1)
       {
         printf("stack is empty");
         getch();
          return(0);
       }
       else
      {
         item=stack[top];
         top--;
       }
      return(item);
   }

/*
OUTPUT:Enter a valid postfix expression ab+c*
                 Enter the value of a 2
                 Enter the value of b 3
                 Enter the value of c 4
                 Result of ab+c* 20

*/

No comments:

Post a Comment