Part of the series

Several example codes

~2 min read • Updated Sep 17, 2025

Magic Square Definition

A magic square is an n×n matrix where:
- Each cell contains a unique integer from 1 to
- The sum of each row, each column, and both diagonals is the same
This algorithm works for odd values of n.


Magic Square Construction Rules:

  1. Start: Place the number 1 in the middle column of the first row.
  2. Move: For each next number, move diagonally one step up and one step left.
  3. If occupied: If the target cell is already filled, move one step directly down instead.
  4. If out of bounds: If moving diagonally goes outside the matrix, wrap around to the opposite edge of the row or column.
  5. If both row and column are out of bounds: Move one step directly down from the last position.

Python Code:


def generate_magic_square(n):
    if n % 2 == 0:
        raise ValueError("Magic square generation only works for odd n.")

    square = [[0] * n for _ in range(n)]
    num = 1
    row, col = 0, n // 2  # Step A

    while num <= n * n:
        square[row][col] = num
        num += 1

        next_row = (row - 1) % n  # Step B + wrap
        next_col = (col - 1) % n

        if square[next_row][next_col] != 0:  # Step C
            row = (row + 1) % n
        else:
            row, col = next_row, next_col

    return square

# Display the magic square
n = int(input("Enter an odd number n: "))
magic = generate_magic_square(n)
print("\nMagic Square:")
for row in magic:
    print(row)

Sample Output (n = 3):


Magic Square:
[8, 1, 6]
[3, 5, 7]
[4, 9, 2]

Explanation:

Each number from 1 to is placed according to the diagonal rule.
If the diagonal cell is occupied or out of bounds, the algorithm adjusts by moving down or wrapping around.
The final matrix satisfies the magic condition: all rows, columns, and diagonals have equal sums.


Written & researched by Dr. Shahin Siami