Write a C++ program to create a class which contains two dimensional integer array of size mXn. Write a member function to display sum of all elements of entered matrix. (Use Dynamic Constructor for allocating memory 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 r,c,i,j;
   int **a; //double pointer a
arr()
   {
    cout<<"Enter how many rows: ";
      cin>>r;
      cout<<"Enter how many columns: ";
      cin>>c;
      a=new int *[r];  //allocate memory dynamically for row
      for(i=0;i<r;i++)
      {
      a[i]=new int [c]; ////allocate memory dynamically for column
      }
      for(i=0;i<r;i++)
      {
      for(j=0;j<c;j++)
         {
          cout<<"Enter an element: ";
          cin>>a[i][j];
         }
      }
   }
   void dis() //display 2d array
   {
      for(i=0;i<r;i++)
      {
      for(j=0;j<c;j++)
         {
          cout<<a[i][j]<<" ";
         }
         cout<<endl;
      }
   }
   ~arr()  
   {
    delete a;  //destriction of 2d array dynamically
      cout<<"matrix destroyed succesfully.";
      getch();
   }

};
int main()
{
   arr o;
   o.dis();
   getch();
   return(0);
}

0 Comments