I know the how to fill a magic square but there is a problem in the code.
The algorithm is like below:
1-Put number 1 at the second column of first row.
2-Put the next number one upper row and one behind column.
3-If the cell mentioned in the last step was full,put the numebr at one row below at the same column.
This is my code which I don't think is useful:

#include <iostream>
#include <conio.h>
#include <math.h>
using namespace std;
int main(){
	int i,j,n;
	cin>>n;
	int x[n][n];
	for(i=0;i<n;++i)
		for(j=0;j<n;++j)
			x[i][j]=0;
	i=0;
	j=n/2;
	x[i][j]=1;
	for(int p=2;p<=pow(n,2);++p){
		cout<<i<<" "<<j<<"\n";
		--i;
		--j;
		if(i<0)
			i+=n;
		if(j<0)
			j+=n;
		if(x[i][j]!=0){
			i+=2;
			++j;
		}
		x[i][j]=p;
	}
	cout<<"\n";
	for(i=0;i<n;++i){
		for(j=0;j<n;++j)
			cout<<x[i][j];
		cout<<"\n";
	}
	getch();
	return 0;
}

thanks

Sorry I forgot to talk about the problem.
the problem is at line 19 and the next 8 lines.the first for lines are written to make the number positive and the next four lines are written to change the cell if its full.When it reaches to 7 to be put,both these problems happen and the address becomes for example (4,3) for n=3 which is not in the square.

I know the how to fill a magic square but there is a problem in the code.

We don't...

The algorithm is like below:
1-Put number 1 at the second column of first row.
2-Put the next number one upper row and one behind column.
3-If the cell mentioned in the last step was full,put the numebr at one row below at the same column.

We still don't. Could you make this a little clearer, please?

This article has been dead for over six months. Start a new discussion instead.