Monday, May 19, 2014

C program to perform infix to postfix conversion.


#include<stdio.h>
#include<conio.h>
#include<string.h>
#include<ctype.h>
#define MAX 100
char s[MAX];
int top=-1;

push(char elem)
{
s[++top]=elem;
return top;
}

char pop()
{
return(s[top--]);
}

int pr(char elem)
{
switch(elem)
{
case '#': return 0;
case '(': return 1;
case '+':
case '-': return 2;
case '*':
case '/': return 3;
}
return elem;
}

void main()
{
char infix[50],postfix[50],ch,elem;
int i=0,k=0;
clrscr();
printf("enter infix expression\n");
scanf("%s",infix);
push('#');
while((ch=infix[i++])!='\0')
{
if(ch=='c')
push(ch);
else if(isalnum(ch))
postfix[k++]=ch;
else if(ch==')')
{
while(s[top]!='(')
postfix[k++]=pop();
elem=pop();
}
else
{
while(pr(s[top])>=pr(ch))
postfix[k++]=pop();
push(ch);
}
}
while(s[top]!='#')
postfix[k++]=pop();
postfix[k]='\0';
printf("postfix expression is: %s\n",postfix);
getch();
}

output:

No comments:

Post a Comment