33
Total Posts
3
Categories
24/7
Updated

C++

Write a program to construct a magic square of dimension n × n (n odd).

Published on Dec 22, 2025
#include <iostream>
using namespace std;

int main() {
    int n;
    cout << "Enter an odd number (n): ";
    cin >> n;

    if (n % 2 == 0) {
        cout << "Magic square is possible only for odd n." << endl;
        return 0;
    }

    int magic[50][50] = {0};   // assuming n ≤ 50

    int i = 0;
    int j = n / 2;

    for (int num = 1; num <= n * n; num++) {
        magic[i][j] = num;

        int newi = (i - 1 + n) % n;
        int newj = (j + 1) % n;

        if (magic[newi][newj] != 0) {
            i = (i + 1) % n;
        } else {
            i = newi;
            j = newj;
        }
    }

    cout << "\nMagic Square of size " << n << " × " << n << ":\n";
    for (int r = 0; r < n; r++) {
        for (int c = 0; c < n; c++) {
            cout << magic[r][c] << "\t";
        }
        cout << endl;
    }

    return 0;
}

Documentation

Input

Enter an odd number (n):  3

Output

Magic Square of size 3 × 3:
8   1   6
3   5   7
4   9   2


What is a Magic Square?

A magic square is an arrangement of numbers from 1 to n² such that the sum of numbers in each row, column, and both diagonals is the same.

Magic Constant:

M = n(n2+1) / 2

 

Algorithm (Siamese Method)

  1. Start with number 1 in the middle of the top row

  2. Next number goes up one row and right one column

  3. If moving out of the square, wrap around

  4. If the cell is already occupied, move down one row

  5. Repeat until is placed