Saturday, September 3, 2011

Infix to Postfix


/* program for conversion of  infix into its postfix form
   operators supported '+,-,*,/,%,^,(,)
   and evaluate.
*/

#include<stdio.h>
#include<string.h>
#include<ctype.h>
#define MAX 50

typedef struct stack
{
int data[MAX];
int top;
}stack;

int  precedence(char);
void init(stack *);
int  empty(stack *);
int  full(stack *);
int  pop(stack *);
void push(stack *,int );
int  top(stack *); //value of the top element
int  evaluate(char x,int op1,int op2);
void infix_to_postfix(char infix[],char postfix[]);
void eval_postfix(char postfix[]);
char alpha[30];
int counter=0,value[30];
int search(char x)
{
int i=0;
for(i=0;i<strlen(alpha);i++)
{
if(x==alpha[i])
return(i);
}
return(-1);
}

int main()
 { char infix[30],postfix[30];
   printf("\nEnter an infix expression : ");
   gets(infix);
   fflush(stdin);
   infix_to_postfix(infix,postfix);
   printf("\nPostfix : %s  \n\n",postfix);
   eval_postfix(postfix);
 }

void infix_to_postfix(char infix[],char postfix[])
{ stack s;
char x;
int i,j;//i-index for infix[],j-index for postfix
char token;
init(&s);
j=0;
for(i=0;infix[i]!='\0';i++)
 {     token=infix[i];
if(isalnum(token))
postfix[j++]=token;
else
if(token == '(')
push(&s,'(');
else
if(token == ')')
  while((x=pop(&s))!='(')
postfix[j++]=x;
else
{
while(precedence(token)<=precedence(top(&s)) && !empty(&s))
{
x=pop(&s);
postfix[j++]=x;
}
push(&s,token);
}
}
while(!empty(&s))
{
x=pop(&s);
postfix[j++]=x;
}
postfix[j]='\0';
}




int precedence(char x)
{
if(x == '(')                         return(0);
if(x == '+' || x == '-')             return(1);
if(x == '*' || x == '/' || x == '%') return(2);
return(3);
}
void eval_postfix(char postfix[])
 {
stack s;
char x;
int op1,op2,val,i,check;
init(&s);
printf("\n\nPostfix Expression: %s",postfix);
for(i=0;i<strlen(postfix);i++)
{      x=postfix[i];
if(isalpha(x) )
    {
check=search(x);
if(check==-1)
 {
 printf("\nEnter the value of %c : ",x);
 scanf("%d",&val);
 alpha[counter]=x;value[counter++]=val;
 push(&s,val);
}
else
push(&s,value[check]);

    }
else
{      //pop two operands and evaluate
op2=pop(&s);
op1=pop(&s);
val=evaluate(x,op1,op2);
push(&s,val);
      }
}
val=pop(&s);
printf("\nvalue of expression = %d",val);

}

int evaluate(char x,int op1,int op2)
{
if(x=='+')  return(op1+op2);
if(x=='-')  return(op1-op2);
if(x=='*')  return(op1*op2);
if(x=='/')  return(op1/op2);
if(x=='%')  return(op1%op2);
return -1;
}


void init(stack *s)
{
s->top=-1;
}

int empty(stack *s)
{
if(s->top==-1) return(1);
return(0);
}

int full(stack *s)
{
if(s->top==MAX-1)    return(1);
return(0);
}

void push(stack *s,int x)
{
s->top=s->top+1;
s->data[s->top]=x;
}

int pop(stack *s)
{
int x;
x=s->data[s->top];
s->top=s->top-1;
return(x);
}

int top(stack * p)
{
return(p->data[p->top]);
}


No comments:

Post a Comment