Write a program to convert an infix expression into its equivalent postfix notation
#include <conio.h>
#include <string.h>
#include <stdio.h>
#include <ctype.h>
char operands[50][80],operaA[50];
int topD=-1,topX=-1;
pushd(char *operaC)
{
strcpy(operands[++topX],operaC);
}
char *popd()
{
return(operands[topX--]);
}
pushr(char operar)
{
operaA[++topD]=operar;
}
char popr()
{
return(operaA[topD--]);
}
int empty(int B)
{
if( B == 0) return(1);
return(0);
}
void main()
{
char prefix[50],cha,str[50],opnd1[50],opnd2[50],operar[2];
int i=0,k=0,opndQ=0;
printf("Give an Expression = ");
gets(prefix);
printf("it's Prefix Expression : %s\n",prefix);
while( (cha=prefix[i++]) != '\0')
{
if(isalnum(cha))
{
str[0]=cha; str[1]='\0';
pushd(str); opndQ++;
if(opndQ >= 2)
{
strcpy(opnd2,popd());
strcpy(opnd1,popd());
strcpy(str,"(");
strcat(str,opnd1);
cha=popr();
operar[0]=cha;operar[1]='\0';
strcat(str,operar);
strcat(str,opnd2);
strcat(str,")");
pushd(str);
opndQ-=1;
}
}
else
{
pushr(cha);
if(opndQ==1)opndQ=0;
}
}
if(!empty(topX))
{
strcpy(opnd2,popd());
strcpy(opnd1,popd());
strcpy(str,"(");
strcat(str,opnd1);
cha=popr();
operar[0]=cha;operar[1]='\0';
strcat(str,operar);
strcat(str,opnd2);
strcat(str,")");
pushd(str);
}
printf("Infix Expression: ");
puts(operands[topX]);
getch();}
Example of execution
Give an Expression = 20+8
it's Prefix Expression : 20+8
Infix Expression: ((20)+8)
Comments
Leave a comment