**

Wednesday, 26 February 2014

Program to convert infix to postfix expression

#include<stdio.h>
#include<stdlib.h>
#include<ctype.h>
#include<string.h>
#include<math.h>
#define max 20

char s[max];
int top=0;

int precedence(char element)
                {
                        switch(element)
                        {
                        case '+' :
                        case '-' :return(1);
                        case '*' :
                        case '/' :return(2);
                        case '^' :return(3);
                        case '(' :
                        case '#' :return(0);
                        }
                     }
                    
                   push(char element)
                   {
                   ++top;
                   s[top]=element;
                   }
                  
                   int pop()
                   {
                   char element;
                   element=s[top];
                   --top;
                   return(element);
                   }


int main()
{
char infix[max],ch,postfix[max],element;
int i=0,j=0;
printf("\n Enter the infix expression:  ");
scanf("%s",infix);
push('#');

for(i=0;i<strlen(infix);i++)
        {
        ch=infix[i];
        if(isalnum(ch))   //alphanumeric character
        postfix[j++]=ch;
        else
        if(ch=='(')
                push(ch);
                     else if(ch==')')
                     {
                       while(s[top]!='(')
                        postfix[j++]=pop();
                        element=pop();
                        }
                else
                        {
                        while(precedence(s[top])>=precedence(ch))
                        postfix[j++]=pop();
                        push(ch);
                         }
          }
                while(s[top]!='#')
                postfix[j++]=pop();
                postfix[i]='\0';
                printf("postfix expn is %s \n\n",postfix);
                return 0;
                 }
              

No comments:

Post a Comment