I need to write a program that generates a magic square of an odd number between 3 and 15. I have written out this much code, and when i type in 3 for the number it gives me the correct square. but any other odd number it gives me an error. Help me Im lost lol.
#include <iostream>
#include <iomanip>
using namespace std;
int ReadSquareSize()
{
int x;
cout<<"Enter a positive odd integer square size of 3 or more: ";
while(1)
{
cin>>x;
if(x>=3 && x%2==1)
{
return x;
}
else
{
cout<<"Enter a positive odd integer square size of 3 or more: ";
}
}
cout<<endl;
}
int main()
{
int k,g;
int unit;
int row,col,newRow,newCol;
int n = ReadSquareSize();
int square[n][n];
for(k=0 ; k<n ; k++) {
for(g=0 ; g<n ; g++) {
square[k][g] = 0;
}
}
unit= 1;
row= 1;
col= (n+1)/2;
k= 1;
square[row-1][col-1]=k;
for(k=2 ; k<=n*n ; k++)
{
newRow= row - 1;
newCol= col + 1;
if (newRow==0 && newCol==(n+1))
{
newRow = row + 1;
newCol = n;
row = newRow;
col = newCol;
square[row-1][col-1]=k;
}
else
{
if(newRow==0)
{
newRow= n;
}
if(newCol==(n+1))
{
newCol= 1;
}
if(square [newRow-1][newCol-1]==0)
{
row=newRow;
col=newCol;
square[row-1][col-1]=k;
}
else
{
newRow= row + 1;
newCol= col;
if(newRow==(n+1))
{
newRow= 1;
}
row= newRow;
col= newCol;
square[row-1][col-1]=k;
}
}
}
// print and free the square
for(int i=0; i<n ;i++)
{
for(int j=0; j<n ; j++)
{
cout<<setiosflags(ios::left) << setw (5) << square[i][j];
}
cout<<endl;
delete[] square[i];
}
free(square);
system("pause");
return 0;
}