Skip to content

Commit 5f299b3

Browse files
Merge pull request #8102 from Ctrl-apk/patch-6
Create Sum of diagonals
2 parents 6765057 + cb8b01e commit 5f299b3

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed

Sum of diagonals

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
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+
}

0 commit comments

Comments
 (0)