-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSum of diagonal elements.java
More file actions
43 lines (42 loc) · 1.17 KB
/
Sum of diagonal elements.java
File metadata and controls
43 lines (42 loc) · 1.17 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
// to find the sum of diagonal elements of a square matrix
import java.util.*;
import java.io.*;
class Diagonal
{
public static void main(String a[])
{
int i,j,diagsum=0;
Scanner sc= new Scanner(System.in);
System.out.println("Enter the number of rows and columns in the matrix");
int row = sc.nextInt();
int col = sc.nextInt();
if(row!=col)
System.exit(0);
else
{
int[][] arr = new int [row][col];
System.out.println("Enter the matrix elements");
for(i=0;i<row;i++)
{
for(j=0;j<col;j++)
{
arr[i][j]=sc.nextInt();
}
}
System.out.println("The matrix is");
for(i=0;i<row;i++)
{
for(j=0;j<col;j++)
{
System.out.print(arr[i][j]+" ");
}
System.out.println(" ");
}
for(i=0;i<row;i++)
{
diagsum = diagsum + arr[i][i];
}
System.out.println("The sum of the diagonals is "+diagsum);
}
}
}