File tree Expand file tree Collapse file tree 1 file changed +41
-0
lines changed Expand file tree Collapse file tree 1 file changed +41
-0
lines changed Original file line number Diff line number Diff line change
1
+ import java.util.*;
2
+
3
+ public class DiagonalSum {
4
+ public static void main(String[] args) {
5
+ Scanner scanner = new Scanner(System.in);
6
+
7
+ System.out.print("Enter the size of the square matrix: ");
8
+ int n = scanner.nextInt();
9
+
10
+ int[][] matrix = new int[n][n];
11
+
12
+ System.out.println("Enter the elements of the matrix:");
13
+ for (int i = 0; i < n; i++) {
14
+ for (int j = 0; j < n; j++) {
15
+ matrix[i][j] = scanner.nextInt();
16
+ }
17
+ }
18
+
19
+ int sum = calculateSum(matrix);
20
+ System.out.println("Diagonal Sum: " + sum);
21
+
22
+ scanner.close(); // Close the scanner
23
+ }
24
+
25
+ public static int calculateSum(int[][] matrix) {
26
+ int sum = 0;
27
+ int n = matrix.length; // Assuming square matrix
28
+
29
+ for (int i = 0; i < n; i++) {
30
+ sum = sum + matrix[i][i]; // Primary diagonal
31
+ sum = sum + matrix[i][n - i - 1]; // Secondary diagonal
32
+ }
33
+
34
+ // If the matrix has odd dimensions, subtract the center element
35
+ if (n % 2 != 0) {
36
+ sum -= matrix[n / 2][n / 2]; // Center element is counted twice
37
+ }
38
+
39
+ return sum;
40
+ }
41
+ }
You can’t perform that action at this time.
0 commit comments