Upload files to "OOP/Java/Lab/Week4"
This commit is contained in:
parent
f7cc8cb99a
commit
48775a2c5e
4 changed files with 168 additions and 0 deletions
55
OOP/Java/Lab/Week4/MagicSquareCheck.java
Normal file
55
OOP/Java/Lab/Week4/MagicSquareCheck.java
Normal file
|
@ -0,0 +1,55 @@
|
|||
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.");
|
||||
}
|
||||
}
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue