Wednesday, 22 November 2017

Implement C++ program for expression conversion-
a) infix to prefix, b)prefix to postfix,
c) prefix to infix, d) postfix to infix and e) postfix to prefix.
#include"iostream"
#include"string"
using namespace std;

class post
{
      char a[20];
      int top;
      string s[20];
public:
      post()
      {
            top = -1;
      }
      void push(string );
      string pop();
      void get();
      void post2infix();
      void post2prefix();
};

void post::get()
{
      cout << "Enter a postfix Equation : ";
      cin >> a;
}

void post::push(string s1)
{
      top++;
      s[top] = s1;
}

string post::pop()
{
      string s1;
      s1 = s[top];
      top--;
      return s1;
}

void post::post2infix()
{
      int i = 0;
      string s1, s2, s3, ch;

      while (a[i] != '\0')
      {
            ch = a[i];
            if (a[i] == '+' || a[i] == '-' || a[i] == '*' || a[i] == '/')
            {
                  s1 = pop();
                  s2 = pop();
                  s3 = s2 + a[i] + s1;
                  push(s3);
                  i++;
            }
            else
            {
                  push(ch);
                  i++;
            }
      }

      cout << "Infix Equation is : ";
      for (int m = 0; m <= top; m++)
      {
            cout << s[m];
      }
      cout << endl;
}

void post::post2prefix()
{
      int i = 0;
      string s1, s2, s3, ch;

      while (a[i] != '\0')
      {
            ch = a[i];
            if (a[i] == '+' || a[i] == '-' || a[i] == '*' || a[i] == '/')
            {
                  s1 = pop();
                  s2 = pop();
                  s3 = a[i] + s2 + s1;
                  push(s3);
                  i++;
            }
            else
            {
                  push(ch);
                  i++;
            }
      }

      cout << "Prefix Equation is : ";
      for (int m = 0; m <= top; m++)
      {
            cout << s[m];
      }
      cout << endl;
}

int main()
{
      int x, t;
      post s;
      do
      {
            cout << "\n 1.Insert Equation \n 2.Postfix2Infix \n 3.Postfix2Prefix : ";
            cin >> t;
            switch (t)
            {
            case 1:
                  s.get();
                  break;
            case 2:
                  s.post2infix();
                  break;
            case 3:
                  s.post2prefix();
                  break;

            default:
                  cout << "\n Invalid Input ";
            }
            cout << "\n Display Menu 1.Yes 2.No ";
            cin >> x;
      } while (x == 1);
}


No comments:

Post a Comment