Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Problem 1: Magic Squares: An n x n array, that is filled with integers 1, 2, 3,

ID: 3634070 • Letter: P

Question

Problem 1:

Magic Squares:

An n x n array, that is filled with integers 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 and each value in the array is unique.



16 3 2 13
5 10 11 8
9 6 7 12
4 15 14 1


Write a c++ program that reads in n2 integer values from the user and tests whether they form a magic square when put into an n x n array. You need to test two features:

• does each of the numbers 1 to n2 occur in the user input?
• when the numbers are put into a square, are the sums of the rows, columns and diagonals equal to each other?

Input: n and n2 integer numbers: if the user enters 3, the array has 3 rows and 3 columns and the integers in the array range from 1 to 9. As data validation, be sure the input is in the correct range and that each value is entered only once. (All elements in the array must be unique).

Output: a printout of the n x n array with each row of data on a separate line and a message of whether it is a magic square or not.

Explanation / Answer

public boolean isMagic() 22 { 23 // test if two dimensions are the same 24 if (square.length != square[0].length) 25 { 26 return false; // not n x n 27 } 28 // test that all integers are represented 29 for (int num = 1; num