#include<stdio.h>
#include<conio.h>
#include<string.h>
#define max 50
char exprsn[max];
char pstfx[max];
char stack[max];
int set_prcdnce(char ch)
{
switch(ch)
{
case '^' : return 5;
case '*' : return 4;
case '/' : return 4;
case '+' : return 3;
case '-' : return 3;
default : return 0;
}
}
void main()
{
clrscr();
int flag,i,top=0,tb=0,j=0;
int cpd,ppd;
do
{
flag = 0;
printf("\n Enter the expression : ");
gets(exprsn);
if(strlen(exprsn) > max )
{
printf("\n\n WARNING : Exceeding the limits !! \n\n");
flag = 1;
}
for(i=0;exprsn[i]!='\0';i++)
{
if(exprsn[i]=='(')
tb++;
if(exprsn[i]==')')
tb--;
}
printf("\n\ntb = %d\n",tb);
if(tb != 0)
{
printf("\n\n WARNING : Unequal Right n Left Brackets in the expression !! \n\n");
flag = 1;
}
}while(flag == 1);
printf("\n\n The expression in normal form : ");
puts(exprsn);
int x = strlen(exprsn);
exprsn[x] = ')';
exprsn[x+1] = '\0';
//printf("\n%c\n",exprsn[x]);
x+=1;
stack[top] = '(';
for(i=0;i<=x;i++)
{
switch(exprsn[i])
{
case '(' : top += 1;
stack[top] = exprsn[i];
break;
case ')' : while(stack[top] != '(')
{
pstfx[j] = stack[top];
top -= 1; j++;
}
top -= 1;
break;
case '^' :
case '/' :
case '*' :
case '+' :
case '-' : cpd = set_prcdnce(exprsn[i]);
ppd = set_prcdnce(stack[top]);
if(cpd < ppd)
{
while(cpd<=ppd)
{
if(top == -1) break;
pstfx[j] = stack[top];
top -= 1; j++;
ppd = set_prcdnce(stack[top]);
}
}
top += 1; stack[top] = exprsn[i];
break;
default : pstfx[j] = exprsn[i]; j++;
break;
}
}
pstfx[j] = '\0';
printf("\n\n The expression in postfix form : ");
puts(pstfx);
getch();
}
No comments:
Post a Comment