Friday, January 25, 2013

C Program which converts Postfix expression to Infix Expression

#include<stdio.h>
#include<ctype.h>
#include<stdlib.h>
#define Max 20
char stOper[Max][Max], Opertop=-1;


void pushOperand(char ch[25])
{
  if (Opertop == Max-1)
   {
      printf("Operand Stack is full\n");
   }
   else
   {
     Opertop++;
     strcpy(stOper[Opertop],ch);
   }
}

char* popOperand()
{
   char ch[25];
     if (Opertop==-1)
      {
            printf("Operand Stack is empty\n");
      }
      else
      {
               strcpy(ch,stOper[Opertop]);
               Opertop--;
      }
      return ch;
}

void dispOperandstack()
{
  int k;
  printf("Operand stack Content: ");
  for (k=Opertop; k>=0; k--)
  {
    printf("%s, ", stOper[k]);
  }
  printf("\n");
}



char* PosttoInfix(char s[25])
{
  char ifx[25],ch1[25],ch2[25],ch3[25];
  int i,j;
  i=0; j=0; Opertop=-1;
  while (s[i]!='\0')
  {
    /*if operand is countered print it */
    if ( (s[i]>=97 && s[i]<=122) || (s[i]>=65 && s[i]<=90) || (s[i]>=48 && s[i]<=57) )
    {
      j=0;
      ifx[j]=s[i];
      j++;
      ifx[j]='\0';
      pushOperand(ifx);
    }
    else
    {
      strcpy(ch1,popOperand());
      strcpy(ch2,popOperand());
      j=0;
      ch3[j]=s[i];
      j++;
      ch3[j]='\0';
      strcpy(ifx,"(");
      strcat(ifx,ch2);
      strcat(ifx,ch3);
      strcat(ifx,ch1);
      strcat(ifx,")");
      pushOperand(ifx);
    }
    i++;
  }
  return popOperand();
}


void main()
{
  char s[25], PtoInf[25],prerev[25];
  clrscr();
  printf("enter a Postfix expression\n");
  scanf("%s",s);
  strcpy(PtoInf,PosttoInfix(s));
  printf("Postfix to Infix =%s\n", PtoInf);
  getch();
}

No comments:

Post a Comment