Write a C++ program to create a class which contains single dimensional integer array of given size. Write a member function to display even and odd numbers from a given array. (Use Dynamic Constructor to allocate and Destructor to free memory of an object)

//Note: If you are not using Borland or Turbo C then add the following line after header files :
//using namespace std;

#include<conio.h>
#include<iostream.h>
class arr
{
public:
   int *a,i,n; //declare pointer a
   arr()
   {
    cout<<"Enter how many no in an array: ";
      cin>>n;
      a=new int [n]; //allocating memory dynamically
      for(i=0;i<n;i++)
      {
      cout<<"Enter an elements: ";
      cin>>a[i];
      }
   }
   void dis()
   {
    cout<<"1 D matrix is: "<<endl;
    for(i=0;i<n;i++)
      {
      cout<<a[i]<<" ";
      }
   }
   void check()
   {
   cout<<"\nEven numbers are: "<<endl;
       for(i=0;i<n;i++)
      {

      if(a[i]%2==0)
         {

          cout<<a[i]<<" ";
         }
     }
         cout<<"\nOdd numbers are: "<<endl;
          for(i=0;i<n;i++)
      {

      if(a[i]%2!=0)
         {

          cout<<a[i]<<" ";
         }
     }
   }
   ~arr()  
   {
    delete a;  //memory destroyed dynamically
      cout<<"\n1 D array is destroyed.";
      getch();
   }
};
void main()
{
   arr t; //Instance of class arr is created

   t.dis(); //calling member functions
   t.check();
   getch();
}

0 Comments