Sunday 21 December 2014

Q.WAp to input elements in a 2-D array and then display the sum
of main diagonal elements.

#include<iostream.h>
#include<conio.h>
void main()
{
  clrscr();
  int r,c,i=0,j=0,sum=0;
  int*ptr;
  cout<<"Enter row and column of a matrix";
  cin>>r>>c;
  ptr=new int[r*c];
  cout<<endl<<"Enter elements of the matrix";
  for(i=0;i<r;i++)
  {
  for(j=0;j<c;j++)
  {
  cin>>ptr[i*c+j];
  }
  }
  cout<<endl<<"Matrix form";
  cout<<endl;
  for(i=0;i<r;i++)
  {
  for(j=0;j<c;j++)
  cout<<ptr[i*c+j]<<'\t';
  cout<<endl;
  }
  for(i=0;i<r;i++)
  {
  for(j=0;j<c;j++)
  {
     if(i==j && i+j==r-1)
     sum=sum+ptr[i*c+j];
  }
  }
  sum-ptr[r/2*c/2+c/2];
  cout<<endl<<"The Sum of diagonal elements of a matrix:"<<sum;
  getch();
}

No comments:

Post a Comment