Any expression can be represented using three types of expressions (Infix, Postfix and Prefix). We can also convert one type of expression to another type of expression like Infix to Postfix, Infix to Prefix, Postfix to Prefix and vice versa. To convert any Infix expression into Postfix or Prefix expression we can use the following procedure… Find all the operators in the given Infix Expression. Find the order of operators evaluated according to their Operator precedence. Convert each operator into required type of expression (Postfix or Prefix) in the same order. To convert Infix Expression into Postfix Expression using a stack data structure, We can use the following steps... Read all the symbols one by one from left to right in the given Infix Expression. If the reading symbol is operand, then directly print it to the result (Output). If the reading symbol is left parenthesis '(', then Push it on to the Stack. If the reading symbol is right parenthesis ')', then Pop all the contents of stack until respective left parenthesis is poped and print each poped symbol to the result. If the reading symbol is operator (+ , - , * , / etc.,), then Push it on to the Stack. However, first pop the operators which are already on the stack that have higher or equal precedence than current operator and print them to the result.
#include<stdio.h>
#include<stdlib.h>
void evaluate();
void push(char);
char pop();
int prec(char);
char infix[30], postfix[30], stack[30];
int top = -1;
void main()
{
printf("\nEnter the valid infix expression:\t");
scanf("%s", infix);
evaluate();
printf("\nThe entered infix expression is :\n %s \n", infix);
printf("\nThe corresponding postfix expression is :\n %s \n", postfix);
}
void evaluate()
{
int i = 0, j = 0;
char symb, temp;
push('#');
for(i=0; infix[i] != '\0'; i++)
{
symb = infix[i];
switch(symb)
{
case '(' :
push(symb);
break;
case ')' :
temp = pop();
while(temp != '(' )
{
postfix[j] = temp;
j++;
temp = pop();
}
break;
case '+' :
case '-' :
case '*' :
case '/' :
case '%' :
case '^' :
case '$' :
while( prec(stack[top]) >= prec(symb) )
{
temp = pop();
postfix[j] = temp;
j++;
}
push(symb);
break;
default:
postfix[j] = symb;
j++;
}
}
while(top > 0)
{
temp = pop();
postfix[j] = temp;
j++;
}
postfix[j] = '\0';
}
void push(char item)
{
top = top+1;
stack[top] = item;
}
char pop()
{
char item;
item = stack[top];
top = top-1;
return item;
}
int prec(char symb)
{
int p;
switch(symb)
{
case '#' :
p = -1;
break;
case '(' :
case ')' :
p = 0;
break;
case '+' :
case '-' :
p = 1;
break;
case '*' :
case '/' :
case '%' :
p = 2;
break;
case '^' :
case '$' :
p = 3;
break;
}
return p;
}
Comments
Post a Comment