Tuesday 19 May 2015

c++ program to perform UNION and INTERSECTION operations on two sets by overriding + & * operators

#include<iostream>
//using n amespace std;
class set
{
  int a[20],n;
  public:
      set()
         { }
      set(int n)
         {
          this->n=n;
         }
      void get();
      void show();
      void sort();
      set operator+(set);
      set operator*(set);
};

void set::get()
  {
   cout<<"Enter the set elements\n";
   for(int i=0;i<n;i++)
    cin>>a[i];
   sort();
  }

void set::show()
 {
  for(int i=0;i<n;i++)
   cout<<"\t"<<a[i];
   cout<<endl;
 }
void set::sort()
 {
  int temp;
  for(int i=0;i<n;i++)
   {
    for(int j=i+1;j<n;j++)
     {
       if(a[i]>a[j])
         {
           temp=a[i];
           a[i]=a[j];
           a[j]=temp;
         }
     }
   }
 }

set set::operator*(set s2)
 {
  set s;
  int count=0;
  for(int i=0;i<n;i++)
  {
   for(int j=0;j<s2.n;j++)
    {
     if(a[i]==s2.a[j])
       {
         s.a[count]=a[i];
         count++;
       }
    }
  }
   s.n=count;
   return s;
 }

set set::operator+(set s2)
 {
  set s;
  int flag=0,i,count=0;
  for( i=0;i<n;i++)
   {
     s.a[i]=a[i];
   }
      s.n=n;
      count=n-1;
      for(int j=0;j<s2.n;j++)
       {
        flag=1;
        for(int k=0;k<s.n;k++)
          {
            if(s2.a[j]==s.a[k])
               flag=0;
          }
        if(flag!=0)
         {
           count++;
           s.a[count]=s2.a[j];
           s.n=count;
         }
        }
  s.n=count+1;
  return s;
 }

int main()
 {
  int n,n1;
  cout<<"Enter the size of set A and B\n";
  cin>>n>>n1;
  set s1(n),s2(n1),s3,s4;
    s1.get();
    s2.get();
    cout<<"SET A\n";
    s1.show();
    cout<<"SET B\n";
    s2.show();
    s3=s1+s2;
    cout<<"UNION\n";
    s3.show();
    s4=s1*s2;
    cout<<"INTERSECTION\n";
    s4.show();
  return 1;
 }

No comments:

Post a Comment