Monday, February 9, 2015

Infix to Postfix Expression Conversion

AIM:
          To write a C program to convert the infix expression into postfix expression using  
           stack.

ALGORITHM:
            Step 1: Start the program.
            Step 2: Get the infix expression as input.
Step 3: Read the input from left to right.
 Step 4: If the input is operand then place it in the postfix expression.
Step 5: Else if the input symbol is an operator then check for the operator type and
also the precedence, pop entries from the stack and place them in the
postfix expression until the lowest priority operator is encountered.
Step 6: ‘(‘symbol will be popped from stack only when we get a ‘)’ symbol.
Step 7: When the input is completely read then pop the elements in stack until it
becomes empty.
 Step 8: Display the postfix expression.
Step 9: Stop the program.
              
PROGRAM
#include<stdio.h>
#include<conio.h>
#include<alloc.h>
int top=0,st[20];
char inf[40],post[40];
void postfix();
void push(int);
char pop();        
void main()
{
clrscr();
printf("Enter the infix expression:");
scanf("%s",inf);
postfix();
getch();
}
void postfix()
{int i,j=0;
for(i=0;inf[i]!=0;i++)
{switch(inf[i])
{
case '+':while(st[top]>=1)
post[j++]=pop();
push(1);
break;
case '-':while(st[top]>=1)
post[j++]=pop();
push(2);
break;
case '*':while(st[top]>=3)
post[j++]=pop();
push(3);
break;
case '/':while(st[top]>=4)
post[j++]=pop();
push(4);
break;
case '^':
post[j++]=pop();
push(5);
break;
case '(':push(0);
break;

case ')':while(st[top]!=0)
post[j++]=pop();
top--;
break;
default:
post[j++]=inf[i];
}}
while(top>0)
post[j++]=pop();
printf("\nPostfix expression is =>\n\t\t%s",post);
}void push(int ele)
{
top++;
st[top]=ele;
}char pop()
{int el;
char e;
el=st[top];
top--;
switch(el)
{case 1:
e='+';
break;
case 2:
e='-';
break;
case 3:
e='*';
break;
case 4:
e='/';
break;
case 5:
e='^';
break;
}return(e);
}


OUTPUT
Enter the infix expression:((a+b)*(c+d)*(e/f)^g)
Postfix expression is =>
                ab+cd+*ef/*g^



RESULT: Thus a C program is written to convert infix expression into a postfix
                  expression and executed successfully.  



No comments:

Post a Comment