Professional Documents
Culture Documents
Solution:
# include <stdio.h>
# include <conio.h>
# include <string.h>
# include <ctype.h>
# define size 50
char st[size];
int top=-1;
void main()
{
void convert(char ifix[size], char pofix[size]);
int isop(char ch);
int prece(char ch);
void push(char ch);
char pop();
char ifix[size], pofix[size];
clrscr();
printf("Enter any valid infix expression: ");
fflush(stdin);
scanf("%[^\n]", &ifix);
printf("The entered infix expression is %s", ifix);
convert(ifix, pofix);
printf("\nThe corresponding postfix expression is %s", pofix);
getch();
}
void push(char ch)
{
st[++top]=ch; return;
}
char pop()
{ return st[top--]; }
int isop(char ch)
{
if(ch=='*' || ch=='/' || ch=='%' || ch=='+' || ch=='-') return 1;
else return 0;
}
int prece(char ch)
{
if(ch=='*' || ch=='/' || ch=='%') return 2;
else if(ch=='+' || ch=='-') return 1;
else return 0;
}
void convert (char ifix[size], char pofix[size])
{
int i=0, j=0; char ch, x;
push('(');
strcat(ifix, ")");
ch=ifix[i];
while(ch!='\0')
{
if(ch=='(')
push(ch);
else if (isdigit(ch)||isalpha(ch))
{
pofix[j]=ch;
j++;
}
else if(isop(ch)==1)
{
x=pop();
while(isop(x)==1 && prece(x)>=prece(ch))
{
pofix[j]=x;
j++;
x=pop();
}
push(x);
push(ch);
}
else if(ch==')')
{
x=pop();
while(x!='(')
{
pofix[j]=x;
j++;
x=pop();
}
}
else
{
puts("Invalid expression");
getch();
exit(1);
}
i++;
ch=ifix[i];
}
pofix[j]='\0';
return;
}
Output 1:
Enter any valid infix expression: 5*(6+2)-12/4
The entered infix expression is 5*(6+2)-12/4
The corresponding postfix expression is 562+*124/-
Output 2:
Enter any valid infix expression: A+B*C+(D*E+F)*G
The entered infix expression is A+B*C+(D*E+F)*G
The corresponding postfix expression is ABC*+DE*F+G*+