Stack infix to Postfix in C - Coding is Funny

Stack infix to Postfix in C





#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
 char infix[50],stack[50],e[50],s[50];
 int i,top=0,k=0,j=0,c=0;
clrscr();

 printf("\n\tEnter Infix Notation :");
 gets(infix);

 stack[++top]='(';
 s[c++]=stack[top];

 printf("\n\tPostfix :-\n");
 printf("INFIX\t\tSTACK\t\tEXPRESSION\n");

 for(i=0;infix[i]!=NULL;i++)
 {
  switch(infix[i])
  {
   case '(':
    stack[++top]='(';
    s[c++]=stack[top];
   break;

   case ')':
    while(stack[top]!='(')
    {       e[k++]=stack[top];
          top--; c--;
    }
    top--;c--;
   break;

   case '^':
    while(stack[top]=='^')
    {        e[k++]=stack[top];
          top--; c--;
    }
    stack[++top]=infix[i];
    s[c++]=stack[top];
   break;
   case '*':
   case '/':
    while(stack[top]=='^' || stack[top]=='*' || stack[top]=='/')
    {        e[k++]=stack[top];
           top--;  c--;
    }
     stack[++top]=infix[i];
     s[c++]=stack[top];
   break;

   case '+':
   case '-':
    while(stack[top]=='^' || stack[top]=='*' || stack[top]=='/' || stack[top]=='+' || stack[top]=='-')
    {        e[k++]=stack[top];
           top--;c--;
    }
     stack[++top]=infix[i];
     s[c++]=stack[top];
   break;

   default:

     e[k++]=infix[i];
   break;

   }
   printf("%c\t\t",infix[i]);
   for(j=0;j<c;j++)
   {
   printf("%c",s[j]);
   }         printf("\t\t");
   for(j=0;j<k;j++)
   {
   printf("%c",e[j]);
   }
   printf("\n");

  }

  while(stack[top]!='(')
  {        e[k++]=stack[top];
        top--;  c--;
  }
  e[k]=NULL;
  s[c]=NULL;
  printf("\t\t%s\t\t",s);
  puts(e);

  printf("\n\nCredit by codingisfunny.blogspot.com");
getch();
}

Output:




  • Share: