Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

8. Lo Shu Magic Square The Lo Shu Magic Square is a grid with 3 rows and 3 colum

ID: 3913555 • Letter: 8

Question

8. Lo Shu Magic Square The Lo Shu Magic Square is a grid with 3 rows and 3 columns shown in Figure 7-19 The Lo Shu Magic Square has the following properties: The grid contains the numbers 1 through 9 exactly . The sum of each row, each column, and each diagonal all add up to the same num ber. This is shown in Figure 7-20 In a program, you can simulate a magic square using a two-dimensional array. Write a function that accepts a two-dimensional array as an argument, and determines whether the array is a Lo Shu Magic Square. Test the function in a program. Figure 7-19 Lo Shu Magic Square Figure 7-20 Sums of the rows, columns, and diagonals 2 15 3 5715 8 1615 15 15 15 15

Explanation / Answer

MagicSquare.java

public class MagicSquare {

public static void main(String[] args) {

int[][] square = {

{2, 7, 6},

{9, 5, 1},

{4, 3, 8}};

System.out.printf("Square %s a magic square. %n",

(isMagicSquare(square) ? "is" : "is not"));

}

public static boolean isMagicSquare(int[][] square){

int rowSum[] = new int[square.length];

int colSum[] = new int[square.length];

int diagonalSum1 = 0;

int diagonalSum2 = 0;

for(int i=0; i<square.length; i++){

for(int j=0; j<square[i].length; j++){

rowSum[i] = rowSum[i]+square[i][j];

}

}

for(int i=0; i<rowSum.length; i++){

System.out.println("Row "+i+" sum is "+rowSum[i]);

}

for(int i=0; i<square.length; i++){

for(int j=0; j<square[i].length; j++){

colSum[i] = colSum[i]+square[j][i];

}

}

for(int i=0; i<colSum.length; i++){

System.out.println("Column "+i+" sum is "+colSum[i]);

}

for(int i=0; i<square.length; i++){

diagonalSum1 = diagonalSum1+square[i][i];

}

for(int i=0; i<square.length; i++){

diagonalSum2 = diagonalSum2+square[i][square.length-1-i];

}

System.out.println("Diagonal Sum1: "+diagonalSum1);

System.out.println("Diagonal Sum2: "+diagonalSum2);

for(int i=0; i<rowSum.length-1; i++){

if(rowSum[i] != rowSum[i+1])

return false;

}

for(int i=0; i<colSum.length-1; i++){

if(colSum[i] != colSum[i+1])

return false;

}

if(diagonalSum1 != diagonalSum2)

return false;

return true;

}

}

Output:

Row 0 sum is 15
Row 1 sum is 15
Row 2 sum is 15
Column 0 sum is 15
Column 1 sum is 15
Column 2 sum is 15
Diagonal Sum1: 15
Diagonal Sum2: 15
Square is a magic square.

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote