Showing posts with label Infix to Postfix Expression Conversion. Show all posts
Showing posts with label Infix to Postfix Expression Conversion. Show all posts

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;