This is very simple if you think in a simple manner.
A magic square is represented in a matrix form. May be all of you know this formula to satisfy magic square rule i.e. for size of matrix n*n sum of each row or column or diagonal should be n[n*n+1]/2.
means
Example: for order of magic square 4
Now Just think it in a programmitically way!!!
A magic square is represented in a matrix form. May be all of you know this formula to satisfy magic square rule i.e. for size of matrix n*n sum of each row or column or diagonal should be n[n*n+1]/2.
means
for n=3 , sum(row or column or diag) = 15You can say here n is order of magic square.
for n=4 , sum(row or column or diag) = 34
for n=5 , sum(row or column or diag) = 65
Example: for order of magic square 4
16 2 3 13
5 11 10 8
9 7 6 12
4 14 15 1
Now Just think it in a programmitically way!!!
Code: Cpp
void BuildMagicSquare()
{
int order=5,loop;
int MagicMat[5][5];
int SqrOfOrder = order * order;
int nCount=0, mid=order/2;
for(loop=1; loop<=SqrOfOrder ; ++loop)
{
MagicMat[nCount--][mid++] = loop;
if (loop % order == 0)
{
nCount += 2;
--mid;
}
else
{
if (mid==order)
mid -= order;
else if (nCount<0)
nCount += order;
}
}
}
vishnu ganesh
like this


