#include<stdio.h>
#include<conio.h>
#define MAX 50
int main()
{
char a[100],b[MAX],ch;
int top,i;
clrscr();
top=-1;
printf("\nEnter Infix - \n");
gets(a);
for(i=0;a[i]!='\0';i++)
{
if (a[i]=='(')
{
push(b,&top,&a[i]);
}
else if (a[i]==')')
{
while(b[top]!= '(')
{
pop(b,&top,&ch);
printf("%c",ch);
}
pop(b,&top,&ch);
}
else
if (check(a[i])==0)
printf("%c",a[i]);
else
{
if(top==-1)
{
push(b,&top,&a[i]);
}
else
if (priority(a[i]) > priority(b[top]))
{
push(b,&top,&a[i]);
}
else
{
while (priority (a[i])<=priority(b[top]))
{
if (top == -1)
break;
pop(b,&top,&ch);
printf("%c",ch);
}
push(b,&top,&a[i]);
}
}
}
while(top!=-1)
{
pop(b,&top,&ch);
printf("%c",ch);
}
}
int check(char ch)
{
switch(ch)
{
case '^':
case '*':
case '/':
case '%':
case '+':
case '-': return(1);
default : return(0);
}
}
int priority(char opt)
{
switch(opt)
{
case '^' : return(4);
case '*' :
case '/' :
case '%' : return(3);
case '+' :
case '-' :return(2);
case '(' : return(1);
default : return (0);
}
}
int push(char b[MAX],int *top,char *ch)
{
if(*top==MAX-1)
{
return(-1);
}
else
{
(*top)++;
b[*top]=*ch;
return(1);
}
}
int pop(char b[MAX],int *top,char *ch)
{
if (*top==-1)
{
return(-1);
}
else
{
*ch=b[*top];
(*top)--;
return(1);
}
}
Saturday, 28 April 2012
C Program to Convert an Infix Expression into a Postfix Expression
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment