Saturday, February 11, 2017

Program to Convert Infix Expression to Post Fix Expression

Hello there in this post you will learn how to write a program to convert an Infix expression to Post Fix expression. To know about algorithm or methodology please refer to my first blog : http://a2cprogramming.blogspot.in/2017/02/stacks.html

Note1: Use proper braces so that the program will run correctly.
Note2: It is illegal to publish this program or use it in your online content. This program is made by improving and shortening the code. This program is written solely by the blogger using his own intellect. However you can use it for compiling your program.

Here is the code:

#include<stdio.h>         
#include<conio.h>
char stack[30];        /* consider the maximum size in the stack to be 30 */
char ex[30];            /*consider the maximum size in the  post fix expression  to be 30 */
int pointerstack=-1;   /* set pointer to the stack at -1 */
int pointerexp = -1;   /* set pointer to the stack at -1 */
void push(char ch);   /* declare a function to push a character to the stack*/
void pop();                /* declare a function which pops a character from stack and adds it to the postfix                                   expression*/
int priority(char);
void main()
{
char input[30];     /* take a input array to the input expression */
printf("enter the infix expression");
gets(input);        /*read the character input and store it in input array */
for(int i = 0;i<30;i++)    /now run a loop from 0 to input size -1/
{
if(input[i]=='(')           /* if '(' is found push it to the stack */
push(input[i]);
else if((input[i]>='A' && input[i]<='Z')||(input[i]>='a' && input[i]<='z'))
ex[++pointerexp]=input[i];     /* If operand is found add it to the postfix expression */
else if(input[i]=='+' ||input[i]=='-' || input[i]=='/' ||input[i]=='*')
{             /* If operand +-/* is found */


while(priority(stack[pointerstack]) >= priority(input[i]))
pop();
   
push(input[i]);
}
/* Note that  here I have used a switch case without break statement*/
/* We begin from - symbol so all the symbol above it are removed from the stack  and like wise*/
else if(input[i]==')')
{          /* If we find a ')' symbol than remove all elements till '('is found and add them to the postfix             expression */
while(stack[pointerstack]!='(')
{
pop();
}
stack[pointerstack]=' ';    /* Here I removed the '(' symbol also which was not removed in the while                                          loop*/
pointerstack--;
}
}
puts(ex);     /Here We print the final Post Fix Expression/
getch();
}
void push(char ch)
{
stack[++pointerstack]=ch;
}
void pop()
{
char x = stack[pointerstack];
ex[++pointerexp] = x;
stack[pointerstack]= ' ';
--pointerstack;
}
int priority(char ch)
{
if(ch=='(')
return 0;
else if(ch=='+' || ch =='-')
return 1;
else if(ch=='*'|| ch=='/')
return 2;
}
/* Upload Date : 11th Feb 2017.
    Upload Time : 6:29PM */

1 comment: