Evaluation of Postfix Expression

#include<stdio.h>
#include<conio.h>
#include<string.h>
char s[30];
int top=-1;
void push(int);
char pop();

void main()
{
 char ch, postfix[30];
 int i=0,op1,op2;
 clrscr();
 printf("enter postfix exp: ");
 scanf("%s",postfix);
 while((ch=postfix[i++])!='\0')
 {
  if(isdigit(ch))
  push(ch-'0');
  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;
   }
  }
 }
 printf("Result is:\n");
 printf("%d",s[top]);
 getch();
}

void push(int val)
{
 top++;
 s[top]=val;
}

char pop()
{
 char ele;
 if(top==-1)
 return top;
 ele=s[top];
 top--;
 return ele;
}

/* Output:
enter postfix exp: 356+*
Result is:
33
*/

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s