Thursday, November 25, 2010

Magic Square

Building Magic Square is not a serious thing for a beginner.....

First what is the idea behind? Let see...

We need a 3x3 matrix (2 D Array)

The number arrangement will look like the below given table.

8

1

6

3

5

7

4

9

2

From the above table it's confirmed that every order we count (horizontal, vertical, diagonal) we get 15.

Logic

Using three variables.. r, c, and i, r will represent row, c will represent column and i will start from value 1 and upto 9

First find the centre column of the top row. Here it is 3x3 that is 3/2=1.5, hence we take integers it will take only 1

That means

C=3/2=1

By default r will be 0 i.e. a[r][c]=1;

Next

r--;

c++;

when r<0 then r will assigned as 2 (3x3 matrix – 0,1,2)

when c>2 then c will assigned as 0

when multiples of 3 comes (3, 6) only r will be incremented that is

r++

above steps will be repeated till a i becomes 9

you will get astonishing magic square

detailed program

#include <iostream.h>

#include <conio.h>

void main()

{

    int a[3][3], i, r, c;

    clrscr();

    r=0; c=3/2; // 3 represent columns

    for(i=1; i<=9; i++)

    {

        a[r][c]=i;

        if(i%3==0)

        {

            r++;

            continue;

        }

        c++;

        r--;

        if(r<0) r=2;

        if(c>2) c=0;

    }

    cout << "\n\nMagic Square of Order 3 x 3 is \n\n";

    for(r=0; r<3; r++)

    {

        for(c=0; c<3; c++)

        {

            cout << a[r][c] << "\t";

        }

    cout << endl;

    }

getch();

}


 

Hope you will enjoy.....

Try this for 5x5, 7x7, 9x9 and nxn and also try the same with even orders (2x2, 4x4, 6x6 etc..)

6 Comments:

Blogger sabz said...

thanku sir...........

November 25, 2010 at 7:52 PM  
Blogger sabz said...

but sir for higher order its getting wrong for me........

November 25, 2010 at 8:08 PM  
Blogger Adarsh said...

Awesome sir....
You are the best....

November 25, 2010 at 11:16 PM  
Blogger Satheesh Kammath R said...

sabari....i tried lot with higher order..its working...
please send me your codes.. i will check it and correct it...

Its difficult to do with even orders means 2x2, 4x4, 6x6 etc...

thanks for the comment

November 27, 2010 at 8:51 PM  
Blogger KynLavera said...

hye..
i'm from malaysia..
i like your magic square's coding..
but your coding not answering my question..
;(

February 24, 2011 at 5:15 AM  
Anonymous Anonymous said...

you said that here in c=3/2 // 3 represents column so what is the purpose of 3 and how r will be 0 by default plzz explain

August 3, 2015 at 10:51 AM  

Post a Comment

Subscribe to Post Comments [Atom]

<< Home