Conversion of Infix Expressions to Postfix developerIndian.com

Updated:13/01/2024 by Computer Hope

Go Back



Let see A + B * C can be written as (A + (B * C)) to show explicitly that the multiplication has precedence over the addition. On closer observation, however, you can see that each parenthesis pair also denotes the beginning and the end of an operand pair with the corresponding operator in the middle.

Consider once again the expression A + B * C. As shown above, A B C * + is the postfix equivalent. We have already noted that the operands A, B, and C stay in their relative positions. It is only the operators that change position. Let’s look again at the operators in the infix expression. The first operator that appears from left to right is +. However, in the postfix expression, + is at the end since the next operator, *, has precedence over addition. The order of the operators in the original expression is reversed in the resulting postfix expression. Want to learn how we can Conversion of Infix Expressions to Prefix and Postfix¶

Below is Example of Conversion of Infix Expressions to Postfix Expressions


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

void  push (char  ch)
  { if (top == MAX -1)
       return ;
    stack [++top]=ch;
   }

char  pop( )
  {if(top==-1)
       return '\0';
    return stack[top--];
  }

int prece(char ch)
  { if( ch=='/' || ch=='*' )
       return 2;
    if( ch=='+' || ch=='-' )
       return 1;
     else 
        return 0;
  }

void main()
  {
  char in[50],post[50],ch;
  int i=0,j=0,len;
  clrscr();
  printf("\n Enter any expression in infix notation :");
  scanf("%s",in);
  len=strlen(in);
  push('(');
  in[len]=')';
  in[len+1]='\0';
  while(in[i] != '\0')
    {
    if( isalpha(in[i]) )
      post[j++]=in[i];
    else if(in[i]=='(')
      push('(');
    else if(in[i]==')')
     {
     while( (ch=pop()) != '(' )
	post[j++]=ch;
     }
    else if(in[i] != ' ')
     {
     while( prece(ch=pop()) >= prece(in[i]) )
	  post[j++]=ch;
     push(ch);
     push(in[i]);
     }
    i++;
    }
    post[j]='\0';
    printf("\n Postfix Expression=%s",post);
    getch();
  }

Conclusion

In this example, the infix_to_postfix function takes an infix expression as input and returns the corresponding postfix expression. It uses a stack to keep track of operators and follows the rules of precedence and associativity to build the postfix expression.
The example infix expression is "a + b * (c ^ d - e) / f", and the resulting postfix expression is obtained using the infix_to_postfix function.