|
CPP Program To Implement Postfix Expression Evaluation : |
|
#include
#include
#include
#include
#include
#include
#define MAX 50
class PostFix
{
public:
struct postfix
{
int stack[MAX];
int top,nn;
char *s;
}q;
void initpostfix(struct postfix *);
void setexpr(struct postfix *,char *);
void push(struct postfix *,int);
int pop(struct postfix *);
void calculate(struct postfix *);
void show(struct postfix);
};
void PostFix :: initpostfix(struct postfix *p)
{
p->top=-1;
}
void PostFix :: setexpr(struct postfix *p,char *str)
{
p->s=str;
}
void PostFix :: push(struct postfix *p,int item)
{
if(p->top==MAX-1)
cout<<"\n Stack is full";
else
{
p->top++;
p->stack[p->top]=item;
}
}
int PostFix :: pop(struct postfix *p )
{
int data;
if(p->top==-1)
{
cout<<"\nStack is empty";
return NULL;
}
data=p->stack[p->top];
p->top--;
return(data);
}
void PostFix :: calculate(struct postfix *p)
{
int n1,n2,n3;
while(*(p->s))
{
if(isdigit(*(p->s)))
{
p->nn=*(p->s)-'0';
push(p,p->nn);
}
else
{
n1=pop(p);
n2=pop(p);
switch(*(p->s))
{
case '+':
n3=n2+n1;
break;
case '-':
n3=n2-n1;
break;
case '*':
n3=n2*n1;
break;
case '/':
n3=n2/n1;
break;
case '%':
n3=n2%n1;
break;
default:
cout<<"\n Unknown operator";
getch();
exit(0);
}
push(p,n3);
}
p->s++;
}
}
void PostFix :: show(struct postfix p)
{
p.nn=pop(&p);
cout<<"\n Result is "<
SAMPLE INPUT AND OUTPUT:
________________________________
EVALUATION OF POSTFIX EXPRESSION
---------------------------------------------
DON'T GIVE SPACE INBETWEEN NUMBERS OR OPERATORS
Enter two single digit numbers and a operator
Enter an expression:23*
Result is 6
________________________________
EVALUATION OF POSTFIX EXPRESSION
---------------------------------------------
DON'T GIVE SPACE INBETWEEN NUMBERS OR OPERATORS
Enter two single digit numbers and a operator
Enter an expression:57-
Result is -2
________________________________
EVALUATION OF POSTFIX EXPRESSION
---------------------------------------------
DON'T GIVE SPACE INBETWEEN NUMBERS OR OPERATORS
Enter two single digit numbers and a operator
Enter an expression:45%
Result is 4
|
|
⇓ Student Projects ⇓
⇑ Student Projects ⇑ |