Program to changes an infix expression into its postfix expression in C.

#include<stdio.h>

void push(char);                                /*Declaration of Functions and global variables*/
char pop();
int precedence(char);
int top=-1;
char stack[40];

main()
{
char ch,inp[40],post[40];                      /*Declaration of local variables*/
int i=0,j=0;
printf("Enter the expression\n");
scanf("%s",inp);                                /*Storing the infix expression in a string*/
for(i=0;inp[i]!='';i++)
{
if(inp[i]!='+'&&inp[i]!='-'&&inp[i]!='*'&&inp[i]!='/'&&inp[i]!='$'&&inp[i]!='('&&inp[i]!=')')    /*If the element is an operand, print it*/
post[j++]=inp[i];
if(inp[i+1]!='+'&&inp[i+1]!='-'&&inp[i+1]!='*'&&inp[i+1]!='/'&&inp[i+1]!='$'&&inp[i+1]!='('&&inp[i+1]!=')')
post[j+1]=inp[i+1];
else if(inp[i]=='(')                            /*When '(' encountered, push into stack*/
{
push(inp[i+1]);
}
else if(inp[i+1]==')')                                    /*When ')' encountered, pop until '(' comes*/
{
while(stack[top]!='('&&top>=0)
post[j++]=pop();
pop();
}
else if(top==-1)                             /*If stack is empty push the operator*/
{
push(inp[i+1]);
}
else if(precedence(inp[i+1])>=precedence(stack[top])) /*If stack is non-empty and inputs priority greater than or equal to operator on top of stack then push*/
{
push(inp[i+1]);
}
else                                          /*Else pop until conditions satisfied and push*/                              {
while(precedence(inp[i+1])<precedence(stack[top])&&top>=0)
post[j++]=pop();
push(inp[i+1]);
}



}
while(top>=0)                                   /*Pop all the remaining operators in the stack*/
{
post[j++]=pop();
}
for(i=0;i<j;i++)
{
printf("%c",post[i]);
}
printf("\n");                    /*Print the final expression*/
}

void push(char c)                                /*Defining the push function*/
{
stack[++top]=c;
}
char pop()                                       /*Defining the pop function*/
{
top--;
return stack[top+1];
}

int precedence(char c)                            /*Precedence function returns the operator's priority*/
{
switch(c)
{
case '+':return 1;
case '-':return 2;
case '*':return 3;
case '/':return 4;
case '$':return 5;
case '(':return 0;
}
return 0;
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s