Best C Programming code for converting Infix Expression into Postfix Expression (January,2021)

//Program code for converting Infix expression into Postfix expression

#include<stdio.h>

#define MAX 100

typedef struct stack
{
 char data[MAX];
 int top;
}stack;

int getpriority(char);

int isempty(stack *);
int isfull(stack *);
char pop(stack *);
void push(stack *,char);
char peek(stack *);
void intopost(char [],char []);
void main()
{
char str[50],str1[50];

printf("Enter the infix expression: ");
gets(str);
intopost(str,str1);

printf("Post fix expression is : ");

puts(str1);

}

// Following function is converting infix into postfix notation

void intopost(char str[],char str1[])
{
stack s;
char x;

int i,j;
s.top=-1;

i=j=0;
  while(str[i]!='\0')
  {
    if(isalnum(str[i]))
   str1[j++]=str[i];
    else
       if(str[i] == '(')
    push(&s,'(');
       else
       {
  if(str[i] == ')')
      while((x=pop(&s))!='(')
      str1[j++]=x;
  else
  {
  while(getpriority(str[i])<=getpriority(peek(&s)) && !isempty(&s))
      {
      x=pop(&s);

      str1[j++]=x;
      }
      push(&s,str[i]);
   }
       }
       i++;
  }
  while(!isempty(&s))
    {
    x=pop(&s);

   str1[j++]=x;
    }
   str1[j]='\0';

}

//following function is returning the priority of the operator

int getpriority(char x)
{
   if(x == '(')
 return(0);
   if(x == '+' || x == '-')
 return(1);
   if(x == '*' || x == '/' || x == '%')
 return(2);
   return(3);
}

//following function checking whether the stack is empty or not

int isempty(stack *s)
{
    if(s->top==-1)
 return(1);
    else
 return(0);
}

//following function is checking whether the stack is full or not

int isfull(stack *s)
{
    if(s->top==MAX-1)
 return(1);
    else
 return(0);
}

//following function is inserting value into the stack

void push(stack *s,char x)
{
  s->top=s->top+1;
  s->data[s->top]=x;
}

//following function is extracting one value at a time from the stack

char pop(stack *s)
{
   int x;
   x=s->data[s->top];
   s->top=s->top-1;
   return(x);
}

//following function is returning the top most value in the stack

char peek(stack * s)
{
   return(s->data[s->top]);
}

Leave a Reply