Monday 22 February 2016

Infix to Postfix Conversion

Infix to Postfix Conversion

This is a C program to convert infix expression to postfix.


#include<stdio.h>
#include<conio.h>
#include<string.h>
char stack[10]={0},top=0;
void push(char);
char pop();
int isOp();
int precedence();

void main(){
      int i,j=0;
      char *infix;
      char in;
      int l;
      char *postfix;
      clrscr();
      printf("Enter the string to be conevrted to Postfix:\n");

      scanf("%s",infix);
      l=strlen(infix);
      postfix =(char *)malloc(l*sizeof(char));
      for(i=0;i<l;i++){
   if(isOp(infix[i])){
    if(precedence(stack[top-1])<precedence(infix[i]))
     push(infix[i]);
    else{
     postfix[j++]=pop();
     i--;    // to read the same character again
    }
         }
   else{
    postfix[j++]=infix[i];
   }
     }
     while(top>0){
   postfix[j++]=pop();
     }
     printf("%s\n",postfix);
  getch();
}


void push(char c){
     stack[top]=c;
     top++;
}


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


int isOp(char c){
   if(c=='+' || c=='-' || c=='*' || c=='/' || c=='^')
       return 1;
   else
       return 0;
}


int precedence(char c){
   if(c=='^') return 3;
   else if(c=='/') return 2;
   else if(c=='*') return 1;
   else if(c=='+'||c=='-') return 0;
   return -1;
}

Also See: Postfix evaluation

No comments:

Post a Comment