infix to postfix expression converter in "C" language
program:
#include<stdio.h>
void infix_to_postfix(char[],char[]);
int precedence(char);
void main()
{
char infix[20],postfix[20];
printf("enter infix string : ");
scanf("%s",infix);
infix_to_postfix(infix,postfix);
printf("\npostfix exp= %s",postfix);
}
void infix_to_postfix(char infix[],char postfix[])
{
char s[20],symbol;
int top=-1,i=0,j=0;
while(infix[i]!='\0')
{
symbol=infix[i];
switch(symbol)
{
case '(':++top;
s[top]=symbol;
break;
case ')':while(s[top]!='(')
{
postfix[j++]=s[top];
top--;
}
top--;
break;
case '+':
case '-':
case '*':
case '^':
case '/':
while(precedence(symbol)<=precedence(s[top]) && top!=-1)
postfix[j++]=s[top--];
s[++top]=symbol;
break;
default:postfix[j++]=symbol; //to add operand to postfix exp
}
i++;
}
while(top!=-1)
{
postfix[j++]=s[top];
top--;
}
postfix[j]='\0';
}
int precedence(char x)
{
switch(x)
{
case '+':
case '-':return(1);
case '*':
case '^':return(3);
case '%':
case '/':return(2);
default:return(0);
}
}
Comments
Post a Comment