For those who are not familiar with the classic magic square algorithm: a magic square is a two-dimensional array (nxn) that contains a numerical value between the values 1 and n ^ 2 in each place. Each value can appear only once. In addition, the sum of each row, column, and diagonal must be the same. The input should be odd as I write an odd magic square solution.
I performed the problem, but at the moment it has an unknown error (logical? Output?) That annoyed me for the last hour. The displayed values are very inactive. Any help would be greatly appreciated:
#include<iostream>
#include<iomanip>
using namespace std;
int main()
{
int n;
cout<< "Please enter an odd integer: ";
cin>>n;
int MagicSquare[n][n];
int newRow,
newCol;
int i =0 ;
int j= n / 2;
for ( int value = 1; value <= n*n; value++ )
{
MagicSquare[i][j] = value;
newRow = (i + 1) % n;
newCol = (j + 1) % n;
if ( MagicSquare[newRow][newCol] == 0 )
{
i = newRow;
j = newCol;
}
else
{
i = (i - 1 + n) % n;
}
}
for(int x=0; x<n; x++)
{
for(int y=0; y<n; y++)
cout << MagicSquare[x][y]<<" ";
cout << endl;
}
}
source
share