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.
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..)