Array's

Here is another one I am having a really hard time with.

A magic square of order n is an arrangement of n2 numbers, usually distinct integers, in a square such that the sums of the rows, columns, and diagonals are equal. A normal magic square contains the integers 1, 2, 3, ..., n2.

The sum of a magic square is known as the magic constant, denoted M, and for a normal magic square is given by the formula,
M = (n(n^2+1))/2

The algorithm works like this, which we shall illustrate with an example where n = 3. The first step is to place 1 in row 1, column 1,
In general, the next step is to place the next integer in the square above and to the right of the previous integer—wrapping around when necessary.
Continuing with 3. We now have a problem because 4 cannot be placed above and to the right of 3 because 1 already occupies that square. In this situation, the next integer is placed below the previous integer. The algorithm then continues by placing 5 above and to the right of 4. Then 6. And again, we have a conflict because 7 cannot be placed above and to the right of 6 because 4 already occupies that square, so 7 is placed below 6. Completing the algorithm by placing 8 and 9. You should verify that the sum of each row, column, and diagonal is M = 15, and that this is indeed equal to (n(n2 + 1)) / 2.

Your task is to write a C++ program which, given various values of n, will generate and output the magic square of order n using de la Loubère's algorithm.

The input file will be named magic.in and will contain one odd integer, n, per line, 3 ≤ n ≤ 255. Each line ends with a newline character. The end of the list of integers will be denoted by a line containing the single integer -1 which acts as a sentinel.

The output file will be named magic.out and for each input integer n, the output shall be n+2 lines of text. The first line shall be the string "n□=□" followed by the value of n followed by the string ",□M□=□" followed by the value of M. The □ symbol represents the space character. Following the first line shall be the integers of the magic square with n lines and n integers on each line. Each integer shall be separated from the integer to the left of it by a single space. After the magic square is output, the string "-----" shall be output. Each line of the output file, including the final line, shall end with a newline character.
Hi,

Try to write code.
and share with us your code.
Topic archived. No new replies allowed.