Monday, August 27, 2007

PROGRAMME TO CONVERT INFIX TO PREFIX

/* PROGRAMME TO CONVERT INFIX TO PREFIX */


#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 PREFIX EXPRESSION IS:");
infpre(infix);
getch();
}

infpre(char infix[20])
{
int length,i,a,b,len;
char ch,prefix[20],temp[20];
prefix[0]='\0';
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 '(':
{
a=isp(s.ele[s.tos]);
b=icp(infix[i]);
if(a>=b)
{
ch=pop();
temp[0]=ch;
temp[1]='\0';
strcat(temp,prefix);
strcpy(prefix,temp);
s.tos++;
push(infix[i]);
}
else
{
s.tos++;
push(infix[i]);
}
break;
}
case ')':
{
ch=pop();
while(ch!='(')
{
temp[0]=ch;
temp[1]='\0';
strcat(temp,prefix);
strcpy(prefix,temp);
ch=pop();
}
break;
}
default:
{
len=strlen(prefix);
prefix[len]=infix[i];
prefix[++len]='\0';
}
}}
printf("%s",temp);
}

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);
}}

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

No comments: