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

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 [][1024]);
void magicSquare(int [][1024]);
void drawTable(int [][1024]);
int isWritable(int);
int outOfBounds(int, int);

int main()
{
do
{
cin >> size;
} while(size % 2 == 0);

create();

return 0;
}

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

void fillWithZero(int _array[][1024])
{
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[][1024])
{
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[][1024])
{
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;
}
}```

###### C Program to Check whether entered matrix is magic square or not
Samath | Jan 03, 2017
###### C Program to Calculate Area of Square
Samath | Jan 02, 2017
###### Square and Cube Class in C++
Samath | Jan 01, 2015
###### C Program to print table of n and square of n using pow() Function
Samath | Jan 02, 2017
###### Write a C program to Print Square of Each Element of 2D Array Matrix
Samath | Jan 04, 2017
###### Java program that calculates the square, cube, and fourth power of a number
Samath | Feb 08, 2021