Magic Square

asadullah.ansari's Avatar author of Magic Square
This is an article on Magic Square in C++.
Rated 5.00 By 2 users
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
for n=3 , sum(row or column or diag) = 15
for n=4 , sum(row or column or diag) = 34
for n=5 , sum(row or column or diag) = 65
You can say here n is order of magic square.

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
0
alramesh's Avatar
Go4Expert Member
I think this will work only for odd Order.

means for n=1,3,5,7, etc
0
shabbir's Avatar, Join Date: Jul 2004
Go4Expert Founder
Quote:
Originally Posted by alramesh
I think this will work only for odd Order.

means for n=1,3,5,7, etc
Quote:
Originally Posted by debleena_doll2002
Yes !!! It will not work for odd order
Now I have a doubt as to for what it will work.
0
debleena_doll2002's Avatar
Ambitious contributor
I putted wrongly!!! It will work for only Odd Order...
For even order it will not work.
0
debleena_doll2002's Avatar
Ambitious contributor
Can you delete my post
Quote:
Yes !!! It will not work for odd order
0
shabbir's Avatar, Join Date: Jul 2004
Go4Expert Founder
Quote:
Originally Posted by debleena_doll2002
Can you delete my post
Done.
0
debleena_doll2002's Avatar
Ambitious contributor
Thanks Shabbir!!!
0
coderzone's Avatar, Join Date: Jul 2004
Team Leader
Admin, do you think this should be an Article because it does not work correctly as well as Nothing is explained.
0
shabbir's Avatar, Join Date: Jul 2004
Go4Expert Founder
No. Because its a contribution and not a query and so it goes into the Article / Tutorial / Source code section. Now how well its explained will make it a contender for the Article of the month.
0
coderzone's Avatar, Join Date: Jul 2004
Team Leader
Agreed