-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmakeMagicSquare.cpp
More file actions
48 lines (37 loc) · 933 Bytes
/
Copy pathmakeMagicSquare.cpp
File metadata and controls
48 lines (37 loc) · 933 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
#include <iostream>
using namespace std;
int main()
{
int dim = 0;
cout << "Please enter the dimension of the magic square: " << endl;
cin >> dim;
int **magicSquare = new int *[dim];
for ( int i = 0; i < dim; ++i ) {
magicSquare[i] = new int[dim]();
}
int num = 1;
magicSquare[0][dim/2] = num++;
int row = dim-1, col = dim/2+1;
for ( int cnt = 1; cnt < dim*dim; ++cnt ) {
magicSquare[row][col] = num++;
int tempRow = row--, tempCol = col++;
if ( row < 0 )
row = dim-1;
if ( col >= dim )
col = 0;
if ( magicSquare[row][col] != 0 ) {
row = tempRow;
col = tempCol;
++row;
}
}
for ( int i = 0; i < dim; ++i ) {
for ( int j = 0; j < dim; ++j ) {
cout << magicSquare[i][j] << " ";
}
cout << endl;
}
for ( int i = 0; i < dim; ++i )
delete [] magicSquare[i];
delete [] magicSquare;
}