Monday, August 27, 2007

PROGRAMME TO CONVERT INFIX EXPRESSION TO POSTFIX

/* PROGRAMME TO CONVERT INFIX EXPRESSION TO POSTFIX
EXPRESSION */


#include<stdio.h>
# define size 20
struct stk
{
char ele[size];
int tos;
};
typedef struct stk stack;
stack s;
main()
{
int len;
char infix[20],ch;
clrscr();
printf("PLEASE ENTER INFIX EMPRESSION:");
scanf("%s",infix);
len=strlen(infix);
infix[len]=')';
infix[++len]='\0';
printf("\n THE POSTFIX EXPRESSION IS:");
infpre(infix);
getch();
}

infpre(char infix[20])
{
int length,i,a,b;
char ch;
s.tos=0;
s.ele[s.tos]='(';
length=strlen(infix);
for(i=0;i<length;i++)
{
switch(infix[i])
{
case '*':
case '+':
case '-':
case '/':
case '^':
case '(':
case '$':
{
a=isp(s.ele[s.tos]);
b=icp(infix[i]);
if(a>=b)
{
ch=pop();
printf("%c",ch);
s.tos++;
push(infix[i]);
}
else
{
s.tos++;
push(infix[i]);

}
break;
}
case ')':
{
ch=pop();
while(ch!='(')
{
printf("%c",ch);
ch=pop();
}
break;
}
default:
printf("%c",infix[i]);
}}}

push(char ch)
{
s.ele[s.tos]=ch;
}

pop()
{
char ch;
ch=s.ele[s.tos];
s.tos--;
return(ch);
}

int isp(char a)
{
switch(a)
{
case '^':return(3);
case '*':
case '/':return(2);
case '+':
case '-':return(1);
case '(':return(0);
case '$':return(5);
}}

int icp(char a)
{
switch(a)
{
case '^':return(4);
case '*':
case '/':return(2);
case '+':
case '-':return(1);
case ')':return(4);
case '$':return(5);
}}

No comments: