Question 3 [30 marks] - Magic squares

Write a program which takes as input an integer n and prints out an n by n "magic square", if n is odd. The following algorithm consttucts "magic" n by n squares, where n is an odd integer. Place a 1 in the middle of the bottom row. After k has been placed in the (i,j) square, put k + 1 in the square to the right and down, wrapping around the borders. However, if the square to the right and down has already been filled, or if you are in the lower right corner, then you must move to the square straight up instead.

For example, for n = 5, the magic square is:

11    18    25     2     9
10    12    19    21     3
 4     6    13    20    22
23     5     7    14    16
17    24     1     8    15

View the source code

Back