Implement conversion from INFIX to POSTFIX and evaluation of POSTFIX
# include<stdio.h>
#include<stdlib.h>
#include<time.h>
#include <cmath>
#include<dos.h>
#define MAX 50
#define BLANK ' '
#define TAB '\t'
void Push_To_Stack(long int Symbol);
int Pop_from_Stack();
void Convert_Infix_to_Postfix();
int EvaulateExpression();
int CheckPriority(char symbol);
int Check_for_Empty();
int Check_for_Space(char Symbol);
char InfixExpr[MAX], PostFixExpr[MAX];
int Stack[MAX];
int TopCnt;
void Convert_Infix_to_Postfix()
{
unsigned int i,p=0;
char next;
char symbol;
for(i=0;i<strlen(InfixExpr);i++)
{
symbol=InfixExpr[i];
if(!Check_for_Space(symbol))
{
switch(symbol)
{
case '(':
Push_To_Stack(symbol);
break;
case ')':
while((next=Pop_from_Stack())!='(')
PostFixExpr[p++] = next;
break;
case '+':
case '-':
case '*':
case '/':
case '%':
case '^':
while( !Check_for_Empty( ) && CheckPriority(Stack[TopCnt])>= CheckPriority(symbol) )
PostFixExpr[p++]=Pop_from_Stack();
Push_To_Stack(symbol);
break;
default:
PostFixExpr[p++]=symbol;
}
}
}
while(!Check_for_Empty( ))
PostFixExpr[p++]=Pop_from_Stack();
PostFixExpr[p]='\0';
}
int CheckPriority(char symbol)
{
switch(symbol)
{
case '(': return 0;
case '+':
case '-': return 1;
case '*':
case '/':
case '%': return 2;
case '^': return 3;
default : return 0;
}
}
void Push_To_Stack(long int Symbol)
{
if(TopCnt>MAX)
{
printf("Stack over-flow\n");
exit(1);
}
Stack[++TopCnt]=Symbol;
}
int Pop_from_Stack()
{
if( Check_for_Empty() )
{
printf("Stack under-flow\n");
exit(1);
}
return (Stack[TopCnt--]);
}
int Check_for_Empty()
{
if(TopCnt==-1)
return 1;
else
return 0;
}
int Check_for_Space(char Symbol)
{
if( Symbol == BLANK || Symbol == TAB )
return 1;
else
return 0;
}
int EvaulateExpression()
{
long int a,b,t,result;
unsigned int i;
for(i=0;i<strlen(PostFixExpr);i++)
{
if(PostFixExpr[i]<='9' && PostFixExpr[i]>='0')
Push_To_Stack(PostFixExpr[i]-'0');
else
{
a=Pop_from_Stack();
b=Pop_from_Stack();
switch(PostFixExpr[i])
{
case '+': t=b+a; break;
case '-': t=b-a;break;
case '*': t=b*a;break;
case '/': t=b/a;break;
case '%': t=b%a;break;
case '^': t=pow(b,a);
}
Push_To_Stack(t);
}
}
result=Pop_from_Stack();
return result;
}
main(void)
{
int Val;
TopCnt=-1;
printf("\n\tEnter Infix Expression : ");
gets(InfixExpr);
Convert_Infix_to_Postfix();
printf("\n\tPostfix Expression : %s\n",PostFixExpr);
Val=EvaulateExpression();
printf("\n\tValue of expression : %d\n",Val);
return 0;
}
Comments
Leave a comment