An n x n matrix that is filled with the whole numbers 1, 2, 3, .. n 2 is a magic
ID: 3549578 • Letter: A
Question
An n x n matrix that is filled with the whole numbers 1, 2, 3, .. n2 is a magic square if the sum of the elements in each row, in each column, and in the two diagonals is the same value.
Here is a magic square where n = 3:
8 1 6
3 5 7
4 9 2
Write a program that reads n2 numbers from standard input and tests whether they form a magic square when put into matrix form. The value of n is NOT an input to the program; n must be determined from the number of inputs.
For example, the input that creates the example matrix above is 8 1 6 3 5 7 4 9 2.
The output is a single word, "true" if the input produces a magic square, "false" otherwise. Your program may assume that each input token is a whole number.
The program must verify:
1. The proper number of input values was provided.
2. Each of the numbers between 1 and n2 occurs exactly once in the input.
3. When the numbers are arranged in a matrix,
Explanation / Answer
import java.util.Scanner;
public class Test_class {
public static void main(String args[])
{
Scanner in = new Scanner(System.in);
System.out.println("Enter a Integer");
int n=in.nextInt();
int array[][]=new int[n][n];
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
System.out.println("Enter the element of Row "+i+" Column "+j);
array[i][j]=in.nextInt();
}
}
int check_var=check(array,n);
if(check_var==1){
System.out.println("true");
}
else
{
System.out.println("false");
}
in.close();
}
public static int check(int array[][],int n){
int checkvar=1;
int sum_row=0;
int sum_diagonal=0;
int sum_column=0;
for(int i=0;i<n;i++){
sum_row+=array[0][i];
sum_column+=array[i][0];
}
int sum_row_check=0;
int sum_col_check=0;
for(int i=0;i<n;i++){
sum_row_check=0;
sum_col_check=0;
for(int j=0;j<n;j++){
sum_row_check+=array[i][j];
sum_col_check+=array[j][i];
}
sum_diagonal+=array[i][i];
if((sum_row_check!=sum_row) || (sum_col_check!=sum_column))
{
checkvar=0;
break;
}
}
if(sum_row!=sum_diagonal){
checkvar=0;
}
return checkvar;
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.