Question: A Magic Square is a square matrix of consecutive integers, such that the integers in each row, each column and each diagonal add up to

A Magic Square is a square matrix of consecutive integers, such that the integers in each row, each column and each diagonal add up to the same sum. For instance, the first 3 x 3 matrix below is a magic square and the rows, columns and diagonal add up to 15. The second 5 x 5 matrix has 25 consecutive integers - starting at 1 - where each row, column and diagonal has the sum of 65.

8

1

6

3

5

7

5

9

2

17

24

1

8

15

23

5

7

14

16

4

6

13

20

22

10

12

19

21

3

11

18

25

2

9

Magic squares have special algorithms that will create a magic square for any size. For the purpose of this question you are only concerned with odd-sized magic squares, like the two above. There are different algorithms for even-sided magic squares. The steps below describe the algorithm for any odd-sized magic square size 3 or larger.

  1. Start number 1 in the top row, middle column.
  2. Place the next number one row higher and one column to the right.
  3. If (the number mod size) = 1, place the next number one row lower. In the5 x 5 square above, size = 5. So, 6 is below 5, 11 is below 10, 16 is below 15,

Wrap around: If the above instructions ask you to place a number:

  • above the first row, place it in the last row.
  • below the last row, place it in the first row.
  • to the right of the last column, place it in the first column.

Write a program to prompt for an odd number n less than 20, and solve that n-sized magic square.

Name the class and file name Magic.

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!