18 Aug 2019

  • August 18, 2019
  • Amitraj

Infix Expression

It follows the scheme of <operand><operator><operand> i.e. an <operator> is preceded and succeeded by an <operand>. Such an expression is termed infix expression. E.g., A+B


Postfix Expression


It follows the scheme of <operand><operand><operator> i.e. an <operator> is succeeded by both the <operand>. E.g., AB+



Algorithm to convert Infix To Postfix


Let, X is an arithmetic expression written in infix notation. This algorithm finds the equivalent postfix expression Y.
  1. Push “(“onto Stack, and add “)” to the end of X.
  2. Scan X from left to right and repeat Step 3 to 6 for each element of X until the Stack is empty.
  3. If an operand is encountered, add it to Y.
  4. If a left parenthesis is encountered, push it onto Stack.
  5. If an operator is encountered ,then:
    1. Repeatedly pop from Stack and add to Y each operator (on the top of Stack) which has the same precedence as or higher precedence than operator.
    2. Add operator to Stack.
      [End of If]
  6. If a right parenthesis is encountered ,then:
    1. Repeatedly pop from Stack and add to Y each operator (on the top of Stack) until a left parenthesis is encountered.
    2. Remove the left Parenthesis.
      [End of If]
      [End of If]
  7. END.

//C program to convert infix into post fix(Reverse polish notation)            


#include<stdio.h>
#define max 50
char s[max];
int top=-1;
void push(char op)
{
if(top==max-1)
printf("Overflow");
else
s[++top]=op;
}
char pop()
{
return s[top--];
}
int pri(char op)
{
switch(op)
{
case '+':
 case '-': return 0;
 case '*':
 case '/': return 1;
 case '^': return 2;
  default:   return-1;
}
}
int main()
{
char ie[max];
int i;
printf("Enter an infix expression:");
scanf("%s", ie);
for(i=0;  ie[i]!='\0'; i++)
{

switch(ie[i])
{
case '(': push(ie[i]);  break;
case '+':
case '-':
case '*':
case '/':
case '^':

while(pri(ie[i])<=pri(s[top]))

printf("%c", pop());
push(ie[i]);

break;
case ')': while(s[top]!='(')
{
               
                 Printf("%c", pop());
                 
}
  pop();
  break;
  default:  printf("%c", ie[i]);   break;
}
}
return 0;

}

INPUT/OUTPUT:-

Enter an infix expression:(a+b*c)
abc*+

Translate

Popular Posts