Program to Evaluate postfix expression using separate header file for operations

				
					STEP 1: create a header file named stack. In this file we declare the class and all the stack
operations.
********************************************
stack.h
*********************************************/
#define Max 10
class stk_class
{
/*declaration of stack data structure*/
struct stack
{
double s[MAX];
int top;
}st;
public:
stk_class();
void push(double val);
double pop();
};
stk_class::stk_class()
{
st.top=0;
}
void stk_class::push(double val)
{
if(st.top+1>=MAX)
cout<<”\n stack is full”;
st.top++;
st.s[st.top]=val;
}
double stk_class::pop()
{
double val;
if(st.top==-1)
cout<<”\n stack is empty\n”;
st.top--;
return(val);l
}
				
			
				
					STEP 2: Program to evaluate a given postfix expression .her the stack using arrays is
implemented in separate file named stack.h

#include<iostream.h>
#include<conio.h>
#include<stdlib.h>
#include<string.h>
#include<math.h>
/*included the header file as stack using array*/
#define size 80
void main()
{
char exp[size];
int len;
double result;
double post(char exp[]);
clrscr();
cout<<”enter the postfix expression\n”;
cin>>exp;
len=strlen(exp);
exp[len]=’$’;/*append $ at the end a end marker*/
result=post(exp);
cout<<”the value of the expression is”<
getch();
exit(0);
}
double post(char exp[])
{
stk_class obj;
char ch,*type;
double result ,val,op1,op2;
int i;
i=0;
ch=exp[i];
while(ch!=’$’)
{
if(ch>=’0’&&ch<=’9’)
type=””operand”:
else if(ch==’+’||ch==’-‘||ch==’^’)
type=”operator”;
if(strcmp(type,”operand”)==0)/* if the character is
operator*/
{
val=ch-48;
obj.push(val);
}
else
if(strcmp(type,”operator”)==0)/* if it is operator*/
{
op2=obj.pop();
op1=obj.pop();
switch(ch)
{
case ‘+’:result=op1+op2;
break;
case ‘-‘:result=op1-op2;

break;
case ‘*;:result=op1*op2;
break;
case ‘/’: result=op1/op2;
break;
case ‘^’:result=pow(op1,op2)
break;
}/*switch*/
obj.push(result);
}
i++;
ch=exp[i];
}/*while*/
result-obj.pop();/*pop the result*/
return(result);
}
				
			

Leave a Reply