Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package Uprajnenie;
- import java.util.Scanner;
- public class DiagonalDifference {
- public static void main(String[] args) {
- Scanner scanner = new Scanner(System.in);
- // Read the size of the matrix
- int n = scanner.nextInt();
- scanner.nextLine(); // Consume newline
- // Initialize the matrix
- int[][] matrix = new int[n][n];
- // Read matrix elements
- for (int i = 0; i < n; i++) {
- String[] rowValues = scanner.nextLine().split(" ");
- for (int j = 0; j < n; j++) {
- matrix[i][j] = Integer.parseInt(rowValues[j]);
- }
- }
- // Calculate the difference between the sums of diagonals
- int primaryDiagonalSum = 0;
- int secondaryDiagonalSum = 0;
- for (int i = 0; i < n; i++) {
- primaryDiagonalSum += matrix[i][i];
- secondaryDiagonalSum += matrix[i][n - 1 - i];
- }
- int difference = Math.abs(primaryDiagonalSum - secondaryDiagonalSum);
- System.out.println(difference);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement