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.
- Push “(“onto Stack, and add “)” to the end of X.
- Scan X from left to right and repeat Step 3 to 6 for each element of X until the Stack is empty.
- If an operand is encountered, add it to Y.
- If a left parenthesis is encountered, push it onto Stack.
- If an operator is encountered ,then:
- 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.
- Add operator to Stack.
[End of If]
- If a right parenthesis is encountered ,then:
- Repeatedly pop from Stack and add to Y each operator (on the top of Stack) until a left parenthesis is encountered.
- Remove the left Parenthesis.
[End of If]
[End of If]
- 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*+