You are on page 1of 3

/*Program to evaluate an postfix expression*/

#include <stdio.h>
#include <conio.h>
#define DEPTH 10
#define LEN 20
/*Structrue definition*/
struct stacks
{
int TOS;
int elements[DEPTH];
};
/*Prototype declaration of various function to be performed on a stack*/
void initialize(struct stacks *);
/*int isFull(struct stacks *);
int isEmpty(struct stacks *);*/
void push(struct stacks *, int);
int pop(struct stacks *);
int peep(struct stacks *);
/*void display(struct stacks *);*/
/*Prototype declaration for function to calculate <oprnd1> <opr> <oprnd2>*/
int calc(int, int, char);
/*Start of main program*/
int main()
{
struct stacks evalexpr;
int /*choice, push_elem, */i=0, oprnd1, oprnd2, opr, val, result=0;
char postfix[LEN], ch;
initialize(&evalexpr);
printf("Enter the postfix expression enclosed in parenthesis:\n");
gets(postfix);
/*puts(postfix);*/
do
{
ch=postfix[i];
if(ch=='('||ch=='{'||ch=='[')
{
push(&evalexpr,ch);
//display(&evalexpr);
}
else if((ch>=65&&ch<=90)||(ch>=97&&ch<=122))
{
printf("Enter value of %c: ",ch);
scanf("%d",&val);
push(&evalexpr,val);
}
else if(ch=='*'||ch=='/'||ch=='+'||ch=='-')
{
oprnd2=pop(&evalexpr);
oprnd1=pop(&evalexpr);
result=calc(oprnd1,oprnd2,ch);
push(&evalexpr,result);
}
else if(ch==')'||ch=='}'||ch==']')
{
printf("The result is %d.\n",peep(&evalexpr));
}
i++;
}while(postfix[i]!='\0');
getch();
return 1;
}
/*End of main program*/
/*Prototype declaration and definition of various function to be performed on a
stack*/
/*Fuction to initialize structure*/
void initialize(struct stacks *evalexpr)
{
evalexpr->TOS=-1;
}
/*Fuction to check whether stack is full or not*/
/*int isFull(struct stacks *evalexpr)
{
if(evalexpr->TOS==(DEPTH-1))
return 1;
else
return 0;
}*/
/*Function to check whether stack is empty or not*/
/*int isEmpty(struct stacks *evalexpr)
{
if(evalexpr->TOS<0)
return 1;
else
return 0;
}*/
/*Fuction to push/insert an element in the stack*/
void push(struct stacks *evalexpr, int push_elem)
{
evalexpr->TOS++;
evalexpr->elements[evalexpr->TOS]=push_elem;
}
/*Function to pop/delete an element from the stack*/
int pop(struct stacks *evalexpr)
{
int temp=evalexpr->elements[evalexpr->TOS];
evalexpr->TOS--;
return temp;
}
/*Function to read the topmost element of the stack*/
int peep(struct stacks *evalexpr)
{
return evalexpr->elements[evalexpr->TOS];
}
/*Function to display the stack*/
/*void display(struct stacks *evalexpr)
{
int i;
printf("Stack: ");
if(evalexpr->TOS<0)
{
printf("Stack empty.");
}
else
{
for(i=0;i<=(evalexpr->TOS);i++)
{
printf("%c\t",evalexpr->elements[i]);
}
}
printf("\n\n");
}*/
/*Function to calculate when an operator is encountered*/
int calc(int oprnd1, int oprnd2, char ch)
{
switch(ch)
{
case '+':
return oprnd1 + oprnd2;
case '-':
return oprnd1 - oprnd2;
case '*':
return oprnd1 * oprnd2;
case '/':
return oprnd1 / oprnd2;
}
}

You might also like