You are on page 1of 1

Stack Program infix to postfix conversion

#include <stdio.h>
#include <ctype.h>
#define size 60
char s[60];
int top = -1;
PUSH(char element)
{
s[++top] = element;
return 0;
}
char POP()
{
return (s[top--]);
}
int pr(char element)
{
switch(element)
{
case'#':return 0;
case'(':return 1;
case'+':
case'-':return 2;
case'*':
case'/':return 3;
}
return 0;
}
int main()
{
char infix[60], postfix[60], ch, element;
int i=0, k=0;
printf("\n\nEnter Infix Expression: ");
scanf("%s",infix);
PUSH('#');
while( (ch=infix[i++]) != '\0')
{
if( ch == '(') PUSH(ch);
else
if(isalnum(ch)) postfix[k++]=ch;
else
if( ch == ')')
{
while( s[top] != '(')
postfix[k++]=POP();
element=POP();
}
else
{
while( pr(s[top]) >= pr(ch) )
postfix[k++]=POP();
PUSH(ch);
}
}
while( s[top] != '#')
postfix[k++]=POP();
postfix[k]='\0';
printf("\n\n Given Infix Expression: %s \n Postfix Expresssion:
%s\n",infix,postfix);
}

You might also like