Write a C program to convert and print a given valid fully parenthesized in fix arithmetic expression to post fix expression, the expression consists of single character (letter or digit) as operands and +, -, * , / as operators, assume that only binary operators are allowed in the expression

 #include<stdio.h>
 #include<conio.h>
 #include<string.h>
 main()
 {
  char ch,stack[50],infix[50];
  char ans='y';
  int i,j,top=0;
  clrscr();
  while((ans=='y')||(ans=='Y'))
  {
   stack[0]='(';
   printf("\n infix to postfix expression");
   printf("\n enter the infix expression");
   gets(infix);
   fflush(stdin);
   j=strlen(infix);
   printf("\nthe postfix expression is :");
   for(i=0;i<j;i++)
   {
    ch=infix[i];
    if(((ch>='0')&&(ch<='9'))||((ch>='a')&&(ch<='z'))||((ch>='A')&&(ch<='Z')))
    printf("%c",ch);
    if(ch=='(')
    stack[++top]=ch;
    if((ch=='*')||(ch=='/'))
    {
     while((stack[top]=='*')||(stack[top]=='/'))
     printf("%c",stack[top--]);
     stack[++top]=ch;
     }
     if((ch=='+')||(ch=='-'))
     {
      while((stack[top]=='*')||(stack[top]=='/')||(stack[top]=='+')||(stack[top]=='-'))
      {
       printf("%c",stack[top]);
       top--;
       }
       stack[++top]=ch;
       }
       if(ch==')')
       {
    while(stack[top]!='(')
    printf("%c",stack[top--]);
    top--;
       }
      }
      while(stack[top]!='(')
      printf("%c",stack[top--]);
      printf("\ndo you want to continue(y/n)");
      scanf("%c",&ans);
      fflush(stdin);
      }
      return 0;
      }

No comments:

Post a Comment