Evaluate Postfix Expression

Description:           This program evaluates a given postfix expression.
 
Primary Inputs:     A postfix expression
Primary Output:    The evaluated result of the given postfix expression.
Platform Used:      Turbo C++ version 3.0, Borland International Inc.
 

#include
#include
#include
#include /*Maximum size of the postfix expression to take*/
#define maxsize 50
struct post
{
double stack[maxsize/2];
char exp[maxsize];
}s;
int top=0;
/*To check if the current character is an operand or not.
Returns True(1) if it is, else returns False(0). */
int isoperand(char);

/* Evaluate the current operator */
double eval(char);

/* Pushes the current character on top of the stack */
void push(double);
void main()
{
int i=0;
double result;
clrscr();
printf("\n Enter the post-fix expression to be evaluated: ");
while((s.exp[i++]=getchar())!='\n');
s.exp[--i]='\0';
printf("\n The original post-fix expression is: %s",s.exp);
for(i=0;s.exp[i]!='\0';i++)
{
/* Check whether the current character is operand or not */
if(isoperand(s.exp[i]))
/* Current character is operand, push it on the stack */
push((double)(s.exp[i]-'0'));
else
{
/* Current character is an operator, evaluate it and push the result back on stack */
result=eval(s.exp[i]);
push(result);
}
}
printf("\n The result of the given post-fix expression is: %f",s.stack[top-1]);
getch();
}
int isoperand(char a)
{
if(('0'<=a)&&(a<='9')) return 1; else return 0; } void push(double a) { s.stack[top++]=a; } double eval(char a) { double op1,op2; op2=s.stack[--top]; op1=s.stack[--top]; switch(a) { case '+':return(op1+op2); case '-':return(op1-op2); case '*':return(op1*op2); case '/':return(op1/op2); case '^':return(pow(op1,op2)); default :printf("\n Invalid operator: %c",a); getch(); exit(0); } return 0; }

 

Rate this post

Leave a Reply