C++ program to find the sum of elements in a matrix

This C++ program finds the sum of all elements in a matrix using pointer. The row and column values of the matrix are read into the variables m and n. Then the program uses for loop to read the elements to the matrix and at the same time the address of the first element of each row is read into the pointer array p[]. Then the program uses nested for loop to calculate the sum of elements row by row and stores it in the variable s. Then the sum is printed to the output screen.


Program


#include<iostream.h>
#include<conio.h>
void main()
{
          int a[10][10],*p[10],m,n,i,j,s=0;
          cout<<"Enter the order of matrics: ";
          cin>>m>>n;
          cout<<"\nEnter the elements\n\n";
          for(i=0;i<m;i++)
          {
                   p[i]=&a[i][0];
                   for(j=0;j<n;j++)
                   {
                             cin>>a[i][j];
                   }
          }
          for(i=0;i<m;i++)
          {
                   for(j=0;j<n;j++)
                   {
                             s=s+*(p[i]+j);
                   }
          }
          cout<<"\nSum of elements: ";
          cout<<s;   

          getch();
}

No comments: