JAVA program to find the sum of diagonal elements of a square matrix
This JAVA program is to find the sum of diagonal elements of a square matrix.
For example, for a 2 x 2 matrix, the sum of diagonal elements of the matrix {1,2,3,4} will be equal to 5.
1 2
3 4
Sum = 1+4 = 5
Logic
Here the procedure is almost same as the sum of elements of a matrix, only one condition needs to be added which is, we add only those elements of the matrix for which row number and column number is same, like 1st row and 1st column, 2nd row and 2nd column and so on(i==j).
Dry Run of the Program
Take input mat[][] and store elements in mat{1,2}{3,4}
Take input ‘row’ and no of rows(row) as 2
Take input ‘col’ and no of columns(col) as 2
Initialize sum=0
1st iteration for(i=0;i<row;i++) i.e. for(i=0;0<2;i++) Outer loop
1st iteration for(j=0;j<col;j++) i.e. for(j=0;0<2;j++) Inner loop
if(i==j) i.e. if(0==0) true
sum=sum+mat[i][j]; i.e. sum=0+mat[0][0] i.e. sum=0+1 i.e. sum=1
2nd iteration for(j=1;j<col;j++) i.e. for(j=1;1<2;j++) Inner loop
if(i==j) i.e. if(0==1) false
2nd iteration for(i=1;i<row;i++) i.e. for(i=1;1<2;i++) Outer loop
1st iteration for(j=0;j<col;j++) i.e. for(j=0;0<2;j++) Inner loop
if(i==j) i.e. if(1==0) false
2nd iteration for(j=1;j<col;j++) i.e. for(j=1;1<2;j++) Inner loop
if(i==j) i.e. if(1==1) true
sum=sum+mat[i][j]; i.e. sum=1+mat[1][1] i.e. sum=1+4 i.e. sum=5
Now we break out of inner loop and then outer loop.
Hence the sum of diagonal elements of a square matrix[1,2][3,4] would be sum=5
Program
import java.util.*; class arr16 { public static void main(String args[]) { Scanner sc = new Scanner(System.in); int i,j,row,col,sum=0; System.out.println("Enter the number of rows:"); row = sc.nextInt(); System.out.println("Enter the number of columns:"); col = sc.nextInt(); int[][] mat = new int[row][col]; System.out.println("Enter the elements of the matrix") ; for(i=0;i<row;i++) { for(j=0;j<col;j++) { mat[i][j] = sc.nextInt(); } } System.out.println("The elements of the matrix") ; for(i=0;i<row;i++) { for(j=0;j<col;j++) { System.out.print(mat[i][j]+"\t"); } System.out.println(""); } for(i=0;i<row;i++) { for(j=0;j<col;j++) { if(i==j) //this condition checks for diagonal { sum = sum + mat[i][j]; } } } System.out.printf("SUM of DIAGONAL elements of the matrix = "+sum) ; } }