(Under Progress)

Program to find sum of individual diagonals of a matrix


#include <iostream.h>
void main()
{
 int A[10][10],i,j,row,col,sd1,sd2l

 // Enter number rows and columns 
cout << "Enter rows and columns:\n";
cin >> row >> col;



 // Loop to accept matrix
cout << "\nEnter matrix row-wise:\n";

for( i=0; i<row; i++ )
{
 for( j=0; j<col; j++ )
 cin >> A[i][j];
}

// Loop to sum main diagonal 
 for( i=0; i<row; i++ )
{
 for( j=0; j<col; j++ )
 { 
   if( i==j )
   sd1 += A[i][j];
 }


// Loop to sum secondary diagonal
for( i=0; i<row; i++ )
{
 for( j=0; j<col; j++ )
 { 
  if( i+j == row-1 )  // You can also use "col-1" in place
  sd2 += A[i][j];     // "row-1" since it is a square matrix 
 }
}

// Display result 

cout << "\nSum of main diagonal elements is " << sd1;
cout << "\nSum of secondary diagonal elements is "<< sd2;

 




  

 
 

Categories