A Magic Square is a two-dimensional array of positive integers such that the sum
ID: 3555545 • Letter: A
Question
A Magic Square is a two-dimensional array of positive integers such that the sum of each row, column,
and diagonal is the same constant. For example,
16
3
2
13
5
10
11
8
9
6
7
12
4
15
14
1
is a magic square whose constant is 34. Write a program that takes 16 integers as inputs.
The program should determine whether or not the square is a magic square and display the
result in a message to the user.
Additionally:
In addition to the matrix above, your program must work for each of these magic squares, without recompiling the code.
2 rows - 2 columns
1
2
3
4
3 rows - 3 columns
3
3
3
3
3
3
3
3
3
5 rows - 5 columns
11
10
4
23
17
18
12
6
5
24
25
19
13
7
1
2
21
20
14
8
9
3
22
16
15
Each of these matrices should be stored in it
16
3
2
13
5
10
11
8
9
6
7
12
4
15
14
1
Explanation / Answer
import java.io.*;
class Magic_Matrix
{
public static void main()throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.print("nnEnter the size of the matrix : ");
int n=Integer.parseInt(br.readLine());
int A[][]=new int[n][n]; // Creating the Magic Matrix
int i,j,k,t;
/*Initializing every cell of the matrix with 0 */
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
A[i][j] = 0;
}
}
/* When the size of the matrix is Odd */
if(n%2!=0)
{
i=0;
j = n/2;
k = 1;
while(k<=n*n)
{
A[i][j] = k++;
i--; // Making one step upward
j++; // Moving one step to the right
if(i<0 && j>n-1) // Condition for the top-right corner element
{
i = i+2;
j--;
}
if(i<0) // Wrapping around the row if it goes out of boundary
i = n-1;
if(j>n-1) // Wrapping around the column if it goes out of boundary
j = 0;
if(A[i][j]>0) // Condition when the cell is already filled
{
i = i+2;
j--;
}
}
}
/* When the size of the matrix is even */
else
{
k = 1;
/* Filling the matrix with natural numbers from 1 till n*n */
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
A[i][j] = k++;
}
}
j = n-1;
for(i=0; i<n/2; i++)
{
/* swapping corner elements of primary diagonal */
t = A[i][i];
A[i][i] = A[j][j];
A[j][j] = t;
/* swapping corner elements of secondary diagonal */
t = A[i][j];
A[i][j] = A[j][i];
A[j][i] = t;
j--;
}
}
/* Printing the Magic matrix */
System.out.println("The Magic Matrix of size "+n+"x"+n+" is:");
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
System.out.print(A[i][j]+ " ");
}
System.out.println();
}
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.