Evaluate postfix expression

#include<stdio.h>
#include<conio.h>
#include<ctype.h>
struct stack
{
	int top;
   int operand[40];
};
int main ()
{
	struct stack s;
   char st[40];
   int i=0,result,op1,op2,value;
   s.top=-1;
   clrscr();
   printf("Enter postfix form: \n");
   while((st[i]=getchar())!='\n')
   {
   	if(isdigit(st[i]))
      {
      	printf("Pushing----- %d\t",st[i]-'0');
         push(&s,st[i]-'0');
      }
      else
      {
      	op2=s.operand[s.top];
         pop(&s);
         printf("\nPoping------ %d\t",op2);
         op1=s.operand[s.top];
         pop(&s);
         printf("Poping------ %d\t",op1);
         printf("\nApplying the operator %c",st[i]);
         switch(st[i])
         {
         	case '+' :result=op1+op2;
            	break;
            case '-' :result=op1-op2;
            	break;
            case '*' :result=op1*op2;
            	break;
            case '/' :result=op1/op2;
            	break;
         }
         printf("\nPushing intermidate result: %d\n\n",result);
         push(&s,result);
      }
      i++;
   }
   printf("\nValue of the postfix expression : %d",result);
   getch();
   return 0;
}

push(ps,n)
struct stack *ps;
int n;
{
	ps->top++;
   ps->operand[ps->top]=n;
}

pop(ps)
struct stack *ps;
{
	ps->top--;
}

Related posts:

Leave a Reply

Your email address will not be published. Required fields are marked *