Wednesday, July 6, 2011

Program to find the sum of the diagonals of the given Matrix


#include<iostream.h>
#include<conio.h>
void main()
{
  clrscr();
  int m[10][10];
  int i,j,n,sld=0,srd=0,sd=0,t=0;
  for(i=0;i<10;i++)
  {
      for(j=0;j<10;j++)
      {
      m[i][j]=0;
      }
  }
  cout<<"Enter size of a square matrix:"<<endl;
  cin>>n;
  cout<<" Enter the two matrices: "<<endl;
  for(i=0;i<n;i++)
  {
      for(j=0;j<n;j++)
      {
    cout<<"Enter element of m1: "<<(i+1)<<(j+1)<<endl;
    cin>>m[i][j];
      }
  }
  cout<<" The matrix is:"<<endl;
  for(i=0;i<n;i++)
  {
      for(j=0;j<n;j++)
      {
     cout<<m[i][j];
      }
      cout<<"\n";
  }
  for(i=0;i<n;i++)
  {
      sld+=m[i][i];
      srd+=m[i][n-i-1];
  }
  if(n%2!=0)
  {
    t=n/2;
    sd=sld+srd-m[t][t];
  }
  else
    sd=sld+srd;
  cout<<"The sum of diagonals of matrix are"<<endl<<"left diagonal\n"<<sld<<endl<<"right diagonal\n"<<srd<<endl<<"sum of the two diagonals"<<sd<<endl;
  getch();
}

No comments:

Post a Comment