WAP to convert an infix expression into its equivalent prefix
notation.
#include <stdio.h>
#include <conio.h>
#include <ctype.h>
#include <string.h>
char XP[80][100],PX[80];
int UpA=-1,upd=-1;
pushd(char *op)
{
strcpy(XP[++upd],op);
}
char *popX()
{
return(XP[upd--]);
}
pushr(char opr)
{
PX[++UpA]=opr;
}
char popr()
{
return(PX[UpA--]);
}
int empty(int q)
{
if( q == 0) return(1);
return(0);
}
void main()
{
char prefix[80],L,str[80],opnd1[80],opm[80],opr[2];
int i=0,k=0,opY=0;
printf("Enter an Expression = ");
gets(prefix);
printf("Prefix Expression is: %s\n",prefix);
while( (L=prefix[i++]) != '\0')
{
if(isalnum(L))
{
str[0]=L; str[1]='\0';
pushd(str); opY++;
if(opY >= 2)
{
strcpy(opm,popX());
strcpy(opnd1,popX());
strcpy(str,"(");
strcat(str,opnd1);
L=popr();
opr[0]=L;opr[1]='\0';
strcat(str,opr);
strcat(str,opm);
strcat(str,")");
pushd(str);
opY-=1;
}
}
else
{
pushr(L);
if(opY==1)opY=0;
}
}
if(!empty(upd))
{
strcpy(opm,popX());
strcpy(opnd1,popX());
strcpy(str,"(");
strcat(str,opnd1);
L=popr();
opr[0]=L;opr[1]='\0';
strcat(str,opr);
strcat(str,opm);
strcat(str,")");
pushd(str);
}
printf("Infix Expression: ");
puts(XP[upd]);
getch();
}
Comments
Leave a comment