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?



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

Answer / 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

More C++ General Interview Questions

Explain stack & heap objects?

0 Answers  


What are the various access specifiers in c++?

0 Answers  


Is c++ the hardest programming language?

0 Answers  


Why c++ does not have finally?

0 Answers  


What is the Maximum Size that an Array can hold?

55 Answers   Adobe, FutureSoft, HCL, Infosys, Satyam, TCS, Wipro,






Can you be bale to identify between straight- through and cross- over cable wiring? And in what case do you use straight- through and cross-over?

0 Answers  


What size is allocated to the union variable?

0 Answers  


Which function should be used to free the memory allocated by calloc()?

0 Answers  


Write any small program that will compile in "C" but not in "C++"?

4 Answers  


What is the output of printf("%d")?

58 Answers   CTS, HCL, Infosys, TCS, Winit, Wipro,


What is the use of register keyword with the variables?

0 Answers  


When should overload new operator on a global basis or a class basis?

0 Answers  


Categories