A square matrix (usually positive integers) with the sum of each row, column, and both main diagonals being the same is called a magic square. This is a C++ project.

**Fact:** The Magic Number(M) is the sum of each row, column, and both main diagonals.

M= n(n^2+1)/2: where n is the size of the square matrix

**Algorithm:**

Step 1. The position of 1 is fixed at (n/2,n-1) in a magic square. Let this position be (p,q).

Step 2. The number 2 will be placed at (p-1,q+1) position. Whenever row position becomes -1 then change it to n-1 and if column position becomes n then change it to 0.

Step 3. If the calculated position is already occupied by a number then decrement the column by 2 and increment the row by 1.

Step 4. Whenever the row position becomes -1 and the column position becomes n, change it to (0,n-2).

**Note: **Magic Square works best with odd size square matrix.

Submitted by Prateek Saini (Prateek)

Download packets of source code on Coders Packet

## Comments