import java.util.*; import java.io.*; public class MagicSquare { public static v
ID: 3634078 • Letter: I
Question
import java.util.*;import java.io.*;
public class MagicSquare {
public static void main(String[] args) {
int n, i, j;
int[][] s;
Scanner input = new Scanner(System.in);
System.out.println("Enter Size of matrix");
n = input.nextInt();
s = new int[n][n];
System.out.println("Enter Values into matrix");
for (i = 0; i < n; i++) {
for (j = 0; j < n; j++) {
s[i][j] = input.nextInt();
}
}
System.out.println("Square is : ");
for (i = 0; i < n; i++) {
for (j = 0; j < n; j++) {
System.out.print(s[i][j]+" ");
}
System.out.println();
}
if (isMagic(s, n)) {
System.out.println("Square is magic ");
} else {
System.out.println("Square is not magic ");
}
}
public static boolean isMagic(int square[][], int n) {
int lastTotal, i, total, j;
lastTotal = 0;
for (i = 0; i < n; i++) {
total = 0;
for (j = 0; j < n; j++) {
total += square[i][j];
}
if (lastTotal == 0) {
lastTotal = total;
} else if (lastTotal != total) {
return false;
}
}
for (j = 0; j < n; j++) {
total = 0;
for (i = 0; i < n; i++) {
total += square[i][j];
}
if (lastTotal != total) {
return false;
}
}
total = 0;
for (i = 0; i < n; i++) {
total += square[i][i];
}
if (lastTotal != total) {
return false;
}
total = 0;
for (i = 0; i < n; i++) {
total += square[i][n - i - 1];
}
if (lastTotal != total) {
return false;
}
return true;
}
}
Explanation / Answer
int foo(int N) { if (N == 0) return 1; else return N * foo(N-1); } int bar(int N) { if (N == 1) return 1; for (int i = 1; iRelated Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.