#include
#define MAX 30
#define TRUE 1
#define FALSE 0
struct stack /* stack declaration */
{
int top;
float items[MAX];
};
float eval(char[]); /* function declarations */
float pop(struct stack *s);
void push (struct stack *s,float);
int isdigit(char);
float oper(char,float,float);
int empty(struct stack *);
void main()
{
char expr[MAX];
clrscr();
printf("\n Enter the postfix expression:");
scanf("%s",expr);
printf("\n Result is %.2f",eval(expr));
getch();
}
/* function to push items to stack */
void push(struct stack *s,float ele)
{
if(s->top==MAX-1)
{
printf("\n stack overflow");
exit(1);
}
else
s->items[++(s->top)]=ele;
}
/* function to pop item from stack */
float pop(struct stack *s)
{
int x;
if(empty(s))
{
printf("\n stack underflow");
getch();
exit(1);
}
else
{
x=s->items[s->top--];
return x;
}
}
/* function to check whether the stack is empty or not */
int empty(struct stack *s)
{
if(s->top==-1)
return(TRUE);
else
return(FALSE);
}
/* function to evaluate postfix expression */
float eval(char expr[])
{
int e,pos;
float opnd1,opnd2,value;
struct stack stk;
stk.top=-1;
for(pos=0;(e=expr[pos])!='\0';pos++)
{
if(isdigit(e))
push(&stk,(float)(e-'0'));
else
{
opnd2=pop(&stk);
opnd1=pop(&stk);
value=oper(e,opnd1,opnd2);
push(&stk,value);
}
}
return(pop(&stk));
}
/* function to evaluate various arithmatic expressions */
float oper(char symb,float opnd1,float opnd2)
{
switch(symb)
{
case'*':
return(opnd1*opnd2);
case'/':
return(opnd1/opnd2);
case'+':
return(opnd1+opnd2);
case'-':
return(opnd1-opnd2);
}
}
/* function to check whether the character is integer */
int isdigit(char symb)
{
return(symb>='0'&&symb<='9');
}
No comments:
Post a Comment