A magic square of order n is an arrangement of n^2 numbers, usually distinct integers, in a square, such that the n numbers in all rows, all columns, and both diagonals sum to the same constant. A magic square contains the integers from 1 to n^2.

The constant sum in every row, column and diagonal is called the magic constant or magic sum, M. The magic constant of a normal magic square depends only on n and has the following value:

M = n(n^2+1)/2

For normal magic squares of order n = 3, 4, 5, …, the magic constants are: 15, 34, 65, 111, 175, 260,

General Rules for defining magic squares are

- In any magic square, the first number i.e. 1 is stored at position (n/2, n-1). Let this position be (i,j). The next number is stored at position (i-1, j+1) where we can consider each row & column as circular array i.e. they wrap around.
- The position of next number is calculated by decremented row number of previous number by 1, and incrementing the column number of previous number by 1. At any time, if the calculated row position becomes -1, it will wrap around to n-1. Similarly, if the calculated column position becomes n, it will wrap around to 0.
- If the magic square already contains a number at the calculated position, calculated column position will be decremented by 2, and calculated row position will be incremented by 1.
- If the calculated row position is -1 & calculated column position is n, the new position would be: (0, n-2).

Based on the above conditions. Here is CPP program to generate magic square of any given number.

/* program to generate magic squre made by : rakesh kuamr */ #include #include using namespace std; // A function to generate odd sized magic squares void magicSquare(int n) { int x[n][n]; int i,j; for(i=0;i<n;i++) for(j=0;j<n;j++) x[i][j]=0; // Initialize position for 1 i = n/2; j = n-1; // One by one put all values in magic square for (int num=1; num <= n*n; ) { if (i==-1 && j==n) //3rd condition { j = n-2; i = 0; } else { //1st condition helper if next number goes to out of square's right side if (j == n) j = 0; //1st condition helper if next number is goes to out of square's upper side if (i < 0) i=n-1; } if (x[i][j]) //2nd condition { j -= 2; i++; continue; } else x[i][j] = num++; //set number j++; i--; //1st condition } // print magic square //printf("The Magic Square for n=%d:\nSum of each row or column %d:\n\n", n, n*(n*n+1)/2); for(i=0; i<n; i++) { for(j=0; j<n; j++) cout<<setw(4)<<x[i][j]; cout<<endl; } } int main() { int n; cout<<"Enter any odd number between 3 to 9 :"; cin>>n; magicSquare(n); return 0; }

Output of the above program is as follows