There is a magic square matrix in such a way that sum of a
column or a row are same like

3 5 2
4 3 3
3 2 5
sum of each column and row is 10.

you have to check that matrix is magic matrix or not?

Answer Posted / hussein

public class MagicSquares {
public static void main(String[] args) {
int magic[][] = { { 3, 5, 2}, { 4, 3, 3}, { 3, 2, 5};
int total = 0, sum, sum1;
for (int r = 0; r < 3; ++r) {
for (int c = 0; c < 3; ++c) {
total += magic[r][c];
if (magic[r][c] < 10)
System.out.print(" " + magic[r][c]);
else
System.out.print(" " + magic[r][c]);
}
System.out.println();
}

int sumrow[] = new int[4];
for (int c = 0; c < 4; ++c)
sumrow[c] = 0;
for (int row = 0; row < 4; row++)
for (int c = 0; c < 4; ++c)
sumrow[row] += magic[row][c];

int sumcol[] = new int[4];
for (int c = 0; c < 4; ++c)
sumcol[c] = 0;
for (int col = 0; col < 4; col++)
for (int r = 0; r < 4; ++r)
sumcol[col] += magic[r][col];

int sumdiag[] = new int[2];
for (int diag = 0; diag < 4; diag++)
sumdiag[0] += magic[diag][diag];
for (int diag = 0; diag < 4; ++diag)
sumdiag[1] += magic[3 - diag][diag];

sum = total / 4;
sum1 = (sum + ((sumdiag[0] + sumdiag[1]) / 2)) / 2;

if (sum1 == sum)
System.out.println("This is a magic square!");
else
System.out.println("This is not a magic square!");

}

Is This Answer Correct ?    7 Yes 0 No



Post New Answer       View All Answers


Please Help Members By Posting Answers For Below Questions

Explain function overloading and operator overloading.

634


What is a hash function c++?

561


Why pointer is used in c++?

626


What apps are written in c++?

614


Which of the following is not a valid declaration for main() a) int main() b) int main(int argc, char *argv[]) c) They both work

613






Can a constructor be private?

590


We all know that a const variable needs to be initialized at the time of declaration. Then how come the program given below runs properly even when we have not initialized p?

593


What is #include cstdlib in c++?

670


How do you initialize a string in c++?

570


What is a constructor in c++ with example?

590


How a new element can be added or pushed in a stack?

589


Is c++ harder than java?

581


If dog is a friend of boy and boy is a friend of house, is dog a friend of house?

561


Why c++ is not a pure oop language?

563


Why do we use iterators?

631