Search code examples
cstackpostfix-notationinfix-notation

Operators not inserting in the stack in C while trying to convert an infix expression to a postfix one


I am trying to implement an infix-to-postfix conversion program. On executing the code I get to see only alpha-numeric characters. Arithmetic operators are not printing. Upon debugging, I found the operators are not inserting in the stack. I couldn't find out the reason behind this.

Any help is appreciated.

#include<stdio.h>
#include <ctype.h>

#define MAX 50

char st[MAX];
int top = -1;
void push(char);
char pop();
int priority(char);

int main()
{
  int i=0;
  char x,s[50];
  printf("Enter infix expression: ");
  gets(s);
  while(s[i]!='\0')
  {
    if(isalnum(s[i]))
      printf("%c",s[i]);
    else if(s[i] == '(')
      push(s[i]);
    else if(s[i] == ')')
    {
      while((x=pop())!='(')
              printf("%c",x);
    }
    else
    {
      while(priority(st[top])>=priority(s[i]))
        printf("%c",pop());
      push(st[i]);
    }
    i++;
  }
  while(top!=-1)
    printf("%c",pop());
}

void push(char x)
{
  st[++top] = x;
}

char pop()
{
  if(top == -1)
    return -1;
  else
    return (st[top--]);
}

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


Solution

  • As you correctly detected on your debugging session, you don't see operators in your postfix expression because you never push() them to your stack.

    In fact

    • in the first if you check for alphanumeric characters
    • in the following else if you check for opening parenthesis
    • in the second else if you check for closing parenthesis
    • in the final else you manage pops from stack... but you didn't push anything! (1)

    What you need to fix is the last else, where you have at least two distinct problems:

    1. You access st[top] without checking top value. You need to manage the case in which top = -1, that would lead to out of bounds access of the stack array and to undefined behavior. I think that in that scenario you just need to push the operator
    2. You push in the stack st[i]. Probably you meant s[i]

    In this way the while analysing the expression becomes

      while(s[i]!='\0')
      {
        if(isalnum(s[i]))
          printf("%c ",s[i]);
        else if(s[i] == '(' )
          push(s[i]);
        else if(s[i] == ')')
        {
          while((x=pop())!='(')
                  printf("%c ",x);
        }
        else
        {
          if( top != -1 )
          {
            while(priority(st[top])>=priority(s[i]))
              printf("%c ",pop());
          }
          push(s[i]);
        }
        i++;
      }
    

    Input:

    4*6+3
    

    Output:

    4 6 * 3 +
    

    (I added a further space after each %c in printfs in order to improve output readability).


    Note: You still have to fix some problems in operators priority management.