Friday, January 25, 2013

C Program which Converts Prefix 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* PretoInfix(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 */
    /*printf("s=%c\n",s[i]);*/
    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,ch1);
      strcat(ifx,ch3);
      strcat(ifx,ch2);
      strcat(ifx,")");
      pushOperand(ifx);
    }
    i++;
  }
  return popOperand();
}

void main()
{
  char s[25],pre[25],PrtoInf[25],prerev[25];
  clrscr();
  printf("enter a Prefix expression\n");
  scanf("%s",s);
  strcpy(prerev,strrev(s));
  strcpy(PrtoInf,PretoInfix(prerev));
  printf("Prefix to Infix =%s\n", PrtoInf);
  getch();
}

No comments:

Post a Comment