Advertisement
Ligh7_of_H3av3n

03. Diagonal Difference

May 17th, 2024
72
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.07 KB | None | 0 0
  1. package Uprajnenie;
  2.  
  3. import java.util.Scanner;
  4.  
  5. public class DiagonalDifference {
  6.     public static void main(String[] args) {
  7.         Scanner scanner = new Scanner(System.in);
  8.  
  9.  
  10.         // Read the size of the matrix
  11.         int n = scanner.nextInt();
  12.         scanner.nextLine(); // Consume newline
  13.  
  14.         // Initialize the matrix
  15.         int[][] matrix = new int[n][n];
  16.  
  17.         // Read matrix elements
  18.         for (int i = 0; i < n; i++) {
  19.             String[] rowValues = scanner.nextLine().split(" ");
  20.             for (int j = 0; j < n; j++) {
  21.                 matrix[i][j] = Integer.parseInt(rowValues[j]);
  22.             }
  23.         }
  24.  
  25.         // Calculate the difference between the sums of diagonals
  26.         int primaryDiagonalSum = 0;
  27.         int secondaryDiagonalSum = 0;
  28.         for (int i = 0; i < n; i++) {
  29.             primaryDiagonalSum += matrix[i][i];
  30.             secondaryDiagonalSum += matrix[i][n - 1 - i];
  31.         }
  32.  
  33.         int difference = Math.abs(primaryDiagonalSum - secondaryDiagonalSum);
  34.         System.out.println(difference);
  35.     }
  36. }
  37.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement