C Program to Evaluate the Postfix Expression...

#include<stdio.h>
#include<string.h>
#define maxi 100

struct stack
{
int ar[maxi];
int t;
};

void push(struct stack *p,int c)
{
 if(p->t==maxi-1){
   printf("\n Stack Overflow.");
   return;
 }
 p->ar[++p->t]=c;
}

int pop(struct stack *p)
{
 if(p->t!=-1){
  return p->ar[p->t--];
 }
}

int peep(struct stack p)
  { return p.ar[p.t]; }

int isoperator(char c)
{
 if(c=='+'||c=='-'||c=='*'||c=='/'||c=='%'||c=='('||c==')')
  return 1;
 else
  return 0;
}

void main()
{
 struct stack s;
 s.t=-1;
 char a[100];
 int i;
printf("Enter any expression..");
 scanf("%s",a);
 for(i=0;i<strlen(a);i++){
 if(!isoperator(a[i])){
  push(&s,a[i]-'0');
 }
 else if(isoperator(a[i])){
 int b,c,ans;
 b=pop(&s);
 c=pop(&s);
 switch(a[i]){
 case '+':{ans=c+b;break;}
 case '-':{ans=c-b;break;}
 case '*':{ans=c*b;break;}
 case '/':{ans=c/b;break;}
 case '%':{ans=c%b;break;}
 }
 push(&s,ans);
 }
}
printf("\nThe result of the expression is..%d",pop(&s));
}

No comments:

Post a Comment