Prog - 4 Infix To Postfix
Prog - 4 Infix To Postfix
#include<stdio.h>
char stack[20];
int top=-1;
void push(char x) {
stack[++top]=x;
}
char pop() {
if(top==-1)
return -1;
else
return stack[top--];
}
int preced(char x) {
if(x=='(')
return 0;
if(x=='+'||x=='-')
return 1;
if(x=='*'||x=='/' ||x=='%')
return 2;
if(x=='$'|| x=='^')
return 3;
return -1;
}
int main() {
char exp[20],x,*e;
printf("Enter the expression: ");
scanf("%s",exp);
e=exp;
printf("Postfix expression: ");
while(*e!='\0')
{
if(isalnum(*e))
printf("%c",*e);
else if(*e=='(')
push(*e);
else if(*e==')') {
while((x=pop())!='(')
printf("%c",x);
}
else {
while(preced(stack[top])>=preced(*e)) {
printf("%c",pop());
}
push(*e);
}
e++;
}
while(top!=-1)
printf("%c",pop());
}
Output:
Enter the expression: (a+(b*c)/(d-e))
Postfix expression: abc*de-/+