Friday, 8 March 2019

CPP-EX18




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)

#include<iostream.h>
#include<conio.h>
class dynamic_arr
{
  int **p;
  int r,c,i,j;
  public:
  dynamic_arr(int x,int y)
  {
             r=x;
             c=y;
             p=new int *[r];
             for(int i=0;i<r;i++)
             {
                        p[i]=new int[c];
              }

            }
            void getval();
            void display();
            void addition();
            dynamic_arr()
                         {
                          cout<<"\n object destroyed";
                          }
 };
 void dynamic_arr::getval()
 {
            int val;
            for(int i=0;i<r;i++)
            {
                        for(int j=0;j<c;j++)
                        {
                        cout<<"\n enter value";
                        cin>>val;
                        p[i][j]=val;
                        }
             }
  }
  void dynamic_arr::display()
  {
             for(int i=0;i<r;i++)
             {
                        for(int j=0;j<c;j++)
                        {
                          cout<<"\t";
                          cout<<p[i][j];
                         }
                         cout<<"\n";
                        }
                        }
                        void dynamic_arr::addition()
                        {
                          int sum=0;
                          for(int i=0;i<r;i++)
                          {
                                     for(int j=0;j<c;j++)
                                     {
                                                sum=sum+p[i][j];
                                     }
                                    }
                                    cout<<"\naddition of all elements:"<<sum;
                        }
                          void main()
                          {
                                    clrscr();
                                    int m,n,val;
                                    cout<<"\n enter rows & columns";
                                    cin>>m>>n;
                                    dynamic_arr d(m,n);
                                    d.getval();
                                    d.display();
                                    d.addition();
                                    getch();
  }