Program 4


Program 4

#include<stdio.h>

#include<conio.h>

typedef enum{lparen,rparen,plus,minus,times,divide,mod,carot,eos,operand}precedence;



int isp[]={0,19,12,12,13,13,13,14,0};

int icp[]={20,19,12,12,13,13,13,14,0};

char s[20];

char st[20];

char infix[20];

char postfix[20];

char symbol;

int i=0;j=0,top=-1,k=-1;

precedence gettoken(void);

void ip(void);



void main()

{

  printf("enter the infix expression\n");

  scanf("%s",infix);

  ip();

  printf("the equivalent postfix expression=%s\n",postfix);

}



precedence gettoken(void)

{

  symbol=infix[i++];

  switch(symbol)

  {

    case'(':return lparen;

    case')':return rparen:

    case'+':return plus;

    case'-':return minus;

    case'/':return divide;

    case'*':return times;

    case'%':return mod;

    case'^'return carot;

    case'\0':return eos;

    default:return operand;

   }

}



void ip(void)

{

  int a,b;

  precedence token;

  char ch;

  s[++top]=eos;

  for(token=gettoken();token!=eos;token=gettoken())

  {

    if(token==operand)

    {

      postfix[j++]=symbol;

    }

    elseif(token==rparen)

    {

      while(s[top]!=lparen)

      {

        postfix[j++]=st[k--];

        top--;

      }

      ch=st[k--];

      top--;

     }

    else

    {

      a=isp[s[top]];

      b=icp[token];

      while(a>=b)

      {

        postfix[j++]=st[k--];

        top--;

        a=isp[s[top]];

        b=icp[token];

      }

      s[++top]=token;

     st[++k]=symbol;

     }

    }

   while((token=s[top--])!=eos)

  {

    postfix[j++]=st[k--];

  }

  postfix[j]='\0';

}

No comments:

Post a Comment