Programming Practice
A magic square of scale n (n is a positive odd integer) is a two-dimensional n´n square matrix with elements from 1 to n2 (no-repetition) such that the sums of the integers in a row, a column, the diagonal, or the anti-diagonal is identical, i.e., the sum is of value (1+n2)n/2. The followings are magic squares of scale 3 and 5:
Magic square of scale 3:
6 | 1 | 8 |
7 | 5 | 3 |
2 | 9 | 4 |
Magic square of scale 5:
15 | 8 | 1 | 24 | 17 |
16 | 14 | 7 | 5 | 23 |
22 | 20 | 13 | 6 | 4 |
3 | 21 | 19 | 12 | 10 |
9 | 2 | 25 | 18 | 11 |
The algorithm of constructing magic square of scale n is described below:
Write a C program to read a positive odd integer n, where 3≤n<20, then generate and output the magic square of scale n. Also, verify the result by adding all elements in each row, each column, the diagonal, and the anti-diagonal. Note that a magic square is symmetric horizontally and vertically with rotating 90o, 180o, or 270o.
Execution example of magic square of scale 5:
Execution example of magic square of scale 9: