Can someone please help me with this program? I don\'t even know where to begin
ID: 3547087 • Letter: C
Question
Can someone please help me with this program? I don't even know where to begin
A. Read from data file
B. Read from keyboard
C. Display Arrays
D. Magic Square (Display sums of each row, column, and diagonal)
An n-by-n array is called a magic square if the sums of each row, each coulumn and diagonal are eqaul. Write a program to
determine if an array is a magic square and use it to determine if either of the arrays below is a magic square. Hint: If at any time of the sums is not equal to the others, the search is complete.
I. Ask for the size of [n]
II. Store values
III Calculate the sum of each row
A. 1, 15, 15, 4
12, 6, 7, 9
8, 10, 11, 5
13, 3, 2, 16
B. 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
these are the algorithms I create so far
store values find the
for(i=0; i<n; i++)
for(j=0; j<n; j++)
{
System.out.println("")
G[i][j]=scan.nextInt();
the magic number
for(i=0; i<n; i++) for(i=0; i<=(2xn+2)-1) i++) sum1=sum1+G[i][j]
for(j=0; j<n; j++) if(sum[i]=sum[i+1]) sum [count]=sum1;
{ { count=count+1;
System.out.println("") flag= false;
G[i][j]=scan.next Int(); break
if (flag)
System.out.println("Magic num.")
else
System.out.println("Not magic num");
Explanation / Answer
Hi,
As per the description you need perform following operations to know whether an input matrix is Magic Square or not.
then only you can call a matrix as magic square.
I guess you already figured the logic for filling user inputs into two dimensional array.
So i will post the code for checking whether an input matrix is magic square or not.
Here i am assuming that two dimentional array is of same dimension. (ex: like array[4][4] or array[5][5] ..etc.).
and if dimension is 1*1 it will always be a Magic Square. So i am not checking for dimension value 1.
bool isMagicSquare = true;
if (dimension != 1)
{
double referenceSum = 0;
double rowSum = 0;
double columnSum = 0;
double diagnolSum1 = 0;
double diagnolSum2 = 0;
for (int i = 0; i < dimension; i++)
{
rowSum = 0;
columnSum = 0;
for (int j = 0; j < dimension; j++)
{
int number = array[i][j]; // Element at I and J
if (i == j)
{
diagnolSum1 += number;
}
if (i + j == dimension - 1)
{
diagnolSum2 += number;
}
rowSum += number;
columnSum += array[j][i]; // Element at J and I
if(i == 0)
{
referenceSum += number;
}
}
if (rowSum != referenceSum || columnSum != referenceSum)
{
isMagicSquare = false;
break;
}
}
if(isMagicSquare)
{
if (diagnolSum1 != referenceSum || diagnolSum2 != referenceSum)
{
isMagicSquare = false;
}
}
}
if (isMagicSquare)
{
System.Out.Println("the input matrix is a Magic Square");
}
else
{
System.Out.Println("the input matrix is not a Magic Square");
}