Go4Expert

Go4Expert (http://www.go4expert.com/)
-   C++ (http://www.go4expert.com/articles/cpp-tutorials/)
-   -   Magic Square (http://www.go4expert.com/articles/magic-square-t8690/)

asadullah.ansari 6Feb2008 18:37

Magic Square
 
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;
        }
    }
}


alramesh 6Feb2008 21:26

Re: Magic Square
 
I think this will work only for odd Order.

means for n=1,3,5,7, etc

shabbir 7Feb2008 17:14

Re: Magic Square
 
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.

debleena_doll2002 7Feb2008 17:36

Re: Magic Square
 
I putted wrongly!!! It will work for only Odd Order...
For even order it will not work.

debleena_doll2002 7Feb2008 17:38

Re: Magic Square
 
Can you delete my post
Quote:

Yes !!! It will not work for odd order

shabbir 7Feb2008 18:29

Re: Magic Square
 
Quote:

Originally Posted by debleena_doll2002
Can you delete my post

Done.

debleena_doll2002 7Feb2008 18:59

Re: Magic Square
 
Thanks Shabbir!!!

coderzone 9Feb2008 12:45

Re: Magic Square
 
Admin, do you think this should be an Article because it does not work correctly as well as Nothing is explained.

shabbir 9Feb2008 12:57

Re: Magic Square
 
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.

coderzone 9Feb2008 13:00

Re: Magic Square
 
Agreed


All times are GMT +5.5. The time now is 19:55.