MIT-Curricular/OOP/Java/Lab/Week4/MagicSquareCheck.java

56 lines
1.5 KiB
Java

import java.util.Scanner;
class MagicSquareCheck {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter the dimension of the square matrix: ");
int n = sc.nextInt();
int a[][] = new int[n][n];
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
System.out.print(
"Enter the element at (" + i + "," + j + "): "
);
a[i][j] = sc.nextInt();
}
}
// sum of the first row (to have a baseline sum)
int sum = 0;
for (int j = 0; j < n; j++) {
sum += a[0][j];
}
// rows, columns, and diagonals
boolean isMagicSquare = true;
int diag1 = 0, diag2 = 0;
for (int i = 0; i < n; i++) {
int rowSum = 0, colSum = 0;
diag1 += a[i][i];
diag2 += a[i][n - 1 - i];
for (int j = 0; j < n; j++) {
rowSum += a[i][j];
colSum += a[j][i];
}
if (rowSum != sum || colSum != sum) {
isMagicSquare = false;
break;
}
}
if (diag1 != sum || diag2 != sum) {
isMagicSquare = false;
}
if (isMagicSquare) {
System.out.println("The matrix is a magic square.");
} else {
System.out.println("The matrix is not a magic square.");
}
}
}