Question
Java language only **Mandatory Rules** Put Descriptive comments on the code displayed on top of previous comments alreadys displayed On Top of Code write summary
Java language only
**Mandatory Rules**
Put Descriptive comments on the code displayed on top of previous comments alreadys displayed
On Top of Code write summary of what code will do in comments
At the end of the code have the output in comment form
I Will thumbs up good Work thanks!
public class MagicSquare {
static int[][] createMagicSquare(int square[][]) {
// Initialize position for 1
int i = 3/2;
int j = 3-1;
// One by one put all values in magic square
for (int num=1; num <= 9; )
{
if (i==-1 && j==3) //3rd condition
{
j = 3-2;
i = 0;
}
else
{
// 1st condition helper if next number
// goes to out of square's right side
if (j == 3)
j = 0;
// 1st condition helper if next number
// is goes to out of square's upper side
if (i < 0)
i=3-1;
}
if (square[i][j]!=0) //2nd condition
{
j -= 2;
i++;
continue;
}
else
square[i][j] = num++; //set number
j++; i--; //1st condition
}
return square;
}
static boolean checkSquare(int[][] square) {
// calculate the sum of
// the prime diagonal
int sum = 0;
for (int i = 0; i < 3; i++)
sum = sum + square[i][i];
// For sums of Rows
for (int i = 0; i < 3; i++) {
int rowSum = 0;
for (int j = 0; j < 3; j++)
rowSum += square[i][j];
// check if every row sum is
// equal to prime diagonal 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 += square[j][i];
// check if every column sum is
// equal to prime diagonal sum
if (sum != colSum)
return false;
}
return true;
}
public static void main(String args[]) {
int square[][]=new int[3][3];
//assigning all values in the array to 0
for(int i=0;i<3;i++) {
for(int j=0;j<3;j++) {
square[i][j]=0;
}
}
square=createMagicSquare(square);
// Print magic square
System.out.println("The magic square is:");
for (int i=0; i<3; i++)
{
for (int j=0; j<3; j++)
System.out.format("%3d ", square[i][j]);
System.out.println("");
}
if(checkSquare(square))
System.out.println("The given square is Lo Shu Magic Square...");
else
System.out.println("The given square is not a Lo Shu Magic Square...");
}
}
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started