DS Experiment No 03
DS Experiment No 03
INPUT SPECIFICATION :
Post expression is been inserted .
OUTPUT SPECIFICATION :
Evaluate the result of postfix expression .
THEORY :
Postfix Expression :
If we move the operators after the operands then it is known as a postfix
expression. In other words, postfix expression can be defined as an
expression in which all the operators are present after the operands
Pogram code :
#include<stdio.h>
#include<conio.h>
#include<string.h>
#define ms 5
struct stackopd
{
int top1;
int arr1[ms];
};
struct stackopr
{
int top2;
char arr2[ms];
};
typedef struct stackopd STKD;
typedef struct stackopr STKR;
int isfulls1(STKD s)
{
if(s.top1 == ms-1)
return 1;
else
return 0;
}
int isemptys1(STKD s)
{
if(s.top1 == -1)
return 1;
else
return 0;
}
int isfulls2(STKR s)
{
if(s.top2 == ms-1)
return 1;
else
return 0;
}
int isemptys2(STKR s)
{
if(s.top2 == -1)
return 1;
else
return 0;
}
char getopr(STKR s)
{
return s.arr2[s.top2];
}
int evaluate(char opr,int x, int y)
{
int i,p=1;
switch(opr)
{
case '+' : return(x+y);
case '-' : return(x-y);
case '*' : return(x*y);
case '/' : return(x/y);
case '%' : return(x%y);
case '^' : for(i=1;i<=y;i++)
p *= x;
return p;
}
}
void main()
{
STKD s1;
STKR s2;
int x,i,len,cnt,a,b,c;
char expr[25],postexpr[25],ch;
clrscr();
printf("Enter the infix expression : ");
scanf("%s",expr);
len = strlen(expr);
cnt=0;
initialize2(&s2);
for(i=0;i<len;i++)
{
ch = expr[i];
if((ch>=48)&&(ch<=57))
postexpr[cnt++] = ch;
else
{
if(isemptys2(s2))
push2(&s2,ch);
else
if(priority(ch) > priority(getopr(s2)))
push2(&s2,ch);
else
if(priority(ch) == priority(getopr(s2)))
{
postexpr[cnt++] = pop2(&s2);
push2(&s2,ch);
}
else
{
postexpr[cnt++] = pop2(&s2);
if(!isemptys2(s2))
{
if(priority(ch) == priority(getopr(s2)))
{
postexpr[cnt++] = pop2(&s2);
push2(&s2,ch);
}
}
else
push2(&s2,ch);
}
}
}
do
{
postexpr[cnt++] = pop2(&s2);
}while(!isemptys2(s2));
postexpr[cnt]='\0';
initialize1(&s1);
for(i=0;i<strlen(postexpr);i++)
{
ch = postexpr[i];
if((ch>=48)&&(ch<=57))
push1(&s1,ch-48);
else
{
b = pop1(&s1);
a = pop1(&s1);
c = evaluate(ch,a,b);
push1(&s1,c);
}
}
printf("\nResult of the expression = %d",pop1(&s1));
getch();
/*
OUTPUT OF PROGRAM :
Enter the infix expression : 2*3+8-9/3%2*5+4^2
POSTFIX expression is 23*8+93/2%5*-42^+
Result of the expression = 25
*/
CONCLUSION :
The postfix expression is been evaluated .