# magic square problem

• 04-28-2009
ranjan
magic square problem
I wanna solve magic square program written in c++. I have everything working except the elements in first column are misplaced.
It should look like
6 1 8
7 5 3
2 9 4

But mine is resulting
2 1 8
6 5 3
7 9 4

My code goes like this:

[code]
#include<iostream>
#include<cmath>

using namespace std;

int main()
{
int size=3;

int magic[3][3];
int row,col;

row=0;
col=size/2;

for(int i=1;i<=size*size;i++)
{
magic[row][col]=i;

row--;
col--;

if(i%size ==0)
{
row+=2;
col++;
}
else
{
if(col==0)
{
col=col+size;
}
else if(row<0)
{
row=row+size;
}
}

}

for(row=0;row<size;row++)
{
for(col=0;col<size;col++)
{
cout<<magic[row][col]<<" ";
if((col+1)%3==0)
cout<<endl;
}
}

return (0);
}
[/code]
Anybody who has specific idea will be greatly appreciated.
Thanks
ranjan
• 04-28-2009
ranjan
anyway i already solved it...thank god! The change was made as shown:
Code:

```  else                 {                         if(col<0)                         {                                 col=col+size;                         }                         else if(row<0)                         {                                 row=row+size;                         }                 }```