Chapter 7 Arrays 8. Lo Shu Magic Square The Lo Shu Magic Square is a grid with 3
ID: 3708545 • Letter: C
Question
Chapter 7 Arrays 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 number. 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 Figure 7-20 15 4 92 15 3 5715 8 1 615 15 15 15 9. PayrollExplanation / Answer
Hello,
for this question , lets first understand, what a primary diagonal is -
Primary diagonal in 2D array is the diagonal formed by elements , where row==col (i.e i==j).
For solving above question , we need to check if the sum of all the columns and rows is equal to the sum of all the elements on primary diagonal.
We do not need to calculate the sum of secondary diagonal because if the rows and columns sum is equal to primary diagonal’s sum it means that secondary diagonal sum is automatically equal.
Below is the code -
import java.util.Scanner;
public class MagicSquare {
static boolean isMagicSquare(int mat[][])
{
int sum = 0;
//sum of primary diagonal
for (int i = 0; i < 3; i++)
sum = sum + mat[i][i];
// For sums of Rows
for (int i = 0; i < 3; i++) {
int rowSum = 0;
for (int j = 0; j < 3; j++)
rowSum += mat[i][j];
// check if every row sum is equal to the primary diagonal's sum.
if (rowSum != sum)
return false;
}
// For sums of Columns
for (int i = 0; i < 3; i++) {
int colSum = 0;
for (int j = 0; j < 3; j++)
colSum += mat[j][i];
// check if every column sum is equal to the primary diagonal's sum.
if (sum != colSum)
return false;
}
return true;
}
// driver program to test above function
public static void main(String[] args)
{
Scanner in=new Scanner(System.in);
int [][] array=new int[3][3];
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
array[i][j]=in.nextInt();
}
}
if (isMagicSquare(array))
System.out.println("Given Matrix is a Magic Square");
else
System.out.println("Given Matrix is not a Magic Square");
}
}