C++ Magic Square Posted by Samath Last Updated: January 05, 2017 1673

A magic square is an arrangement of the numbers from 1 to n^2 (n-squared) in an nxn matrix, with each number occurring exactly once, and such that the sum of the entries of any row, any column, or any main diagonal is the same.The constant sum in every row, column and diagonal is called the magic constant or magic sum, M. The magic constant of a normal magic square depends only on n and has the following value:
M = n(n^2+1)/2

Example:

Magic Square of size 5
----------------------
9   3  22  16  15
2  21  20  14   8
25  19  13   7   1
18  12   6   5  24
11  10   4  23  17
Sum in each row & each column = 5*(5^2+1)/2 = 65

```#include <iostream>
#include <cstdlib>
#include <cmath>

using namespace std;
int size;

void create(void);
void fillWithZero(int []);
void magicSquare(int []);
void drawTable(int []);
int isWritable(int);
int outOfBounds(int, int);

int main()
{
do
{
cout<<"Please enter size: ";
cin >> size;
} while(size % 2 == 0);

create();

return 0;
}

void create()
{
int grid[size];
magicSquare(grid);
drawTable(grid);
}

void fillWithZero(int _array[])
{
int i, j;

for(i = 0; i < size; i++)
{
for(j = 0; j < size; j++)
{
_array[i][j] = 0;
}
}
}

int isWritable(int n)
{
return (n == 0) ? 1 : 0;
}

int outOfBounds(int max, int n)
{
if( n > max )
{
return 1;
}
if ( n < 0 )
{
return -1;
}
return 0;
}

void magicSquare(int grid[])
{
fillWithZero(grid);

int max = size - 1;
int startY = size / 2;
int startX = max;

int col = startY;
int row = startX;

int i;

int lastCol;
int lastRow;

for(i = 1; i <= (size * size); i++)
{
grid[col][row] = i;
lastRow = row;
lastCol = col;
row++;
col++;
if ( outOfBounds(max, row) == 1 )
{
row = 0;
}
if ( outOfBounds(max, col) == 1 )
{
col = 0;
}
if ( ! isWritable(grid[col][row]) )
{
row = lastRow - 1;
col -= 1;
if( outOfBounds(max, row) == -1)
{
row = max;
}
if( outOfBounds(max, col) == -1)
{
col = max;
}
}
}
}

void drawTable(int grid[])
{
int i, j;
for(i = 0; i < size; i++)
{
for(j = 0; j < size; j++)
{
std::cout << grid[i][j] << "\t";
}
std::cout << std::endl;
}
}```