Could you help me to add proper comments // on each line of the code. public cla
ID: 3826851 • Letter: C
Question
Could you help me to add proper comments // on each line of the code.
public class MagicSquare {
public static void main(String[] args) {
int[][] square = {
{ 8, 11, 14, 1},
{13, 2, 7, 12},
{ 3, 16, 9, 6},
{10, 5, 4, 15}
}; // create new square of given size
System.out.printf("The square %s a magic square. %n",
(isMagicSquare(square) ? "is" : "is not"));
}
// return true if the square is magic (all rows, cols have same sum), false otherwise
public static boolean isMagicSquare(int[][] square) {
int rowNum = square.length;
int colNum = 0;
int[][] sum = new int[2][square.length];
boolean isMagic = true;
int diaSum = 0;
for (int i = 0; i < rowNum; ++i) {
colNum = square[i].length;
if (colNum != rowNum) {
isMagic = false;
break;
}
}
for (int i = 0; i < rowNum; ++i) {
for (int j = 0; j < rowNum; ++j) {
sum[0][i] += square[i][j];
sum[1][i] += square[j][i];
if (i == j) {
diaSum += square[i][j];
}
}
}
if(sum[0][0] != sum[1][0]) {
isMagic = false;
}
else if (sum[0][0] != diaSum) {
isMagic = false;
}
for (int i = 0; i < 2; ++i) {
for (int j = 0; j < rowNum - 1; ++j) {
if (sum[i][j] != sum[i][j + 1]) {
isMagic = false;
break;
}
}
}
return isMagic;
}
}
Explanation / Answer
Please find my comment.
If still you have some doubt then comment.
public class MagicSquare {
public static void main(String[] args) {
int[][] square = {
{ 8, 11, 14, 1},
{13, 2, 7, 12},
{ 3, 16, 9, 6},
{10, 5, 4, 15}
}; // create new square of given size
System.out.printf("The square %s a magic square. %n",
(isMagicSquare(square) ? "is" : "is not"));
}
// return true if the square is magic (all rows, cols have same sum), false otherwise
public static boolean isMagicSquare(int[][] square) {
int rowNum = square.length;
int colNum = 0;
int[][] sum = new int[2][square.length];
boolean isMagic = true;
int diaSum = 0;
// checking whether all rows and column length are of same or not
// simply whether it is a square matrix or not
for (int i = 0; i < rowNum; ++i) {
colNum = square[i].length;
if (colNum != rowNum) {
isMagic = false;
break;
}
}
// finding sum of column and rows and diagonal
for (int i = 0; i < rowNum; ++i) {
for (int j = 0; j < rowNum; ++j) {
sum[0][i] += square[i][j]; // rows sum
sum[1][i] += square[j][i]; // column sum
if (i == j) {
diaSum += square[i][j];
}
}
}
if(sum[0][0] != sum[1][0]) { // first row and first column sum check
isMagic = false;
}
else if (sum[0][0] != diaSum) {
isMagic = false;
}
// checking column and rows sum
for (int i = 0; i < 2; ++i) {
for (int j = 0; j < rowNum - 1; ++j) {
if (sum[i][j] != sum[i][j + 1]) {
isMagic = false;
break;
}
}
}
return isMagic;
}
}