-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmagicSquare.cpp
More file actions
98 lines (81 loc) · 2.24 KB
/
Copy pathmagicSquare.cpp
File metadata and controls
98 lines (81 loc) · 2.24 KB
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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
#include <iostream>
#include <cmath>
#include <vector>
using namespace std;
int main()
{
cout << "Please enter the dimension of the magic square: " << endl;
int dim = 0;
cin >> dim;
int **magicSquare = new int *[dim];
for ( int i = 0; i < dim; ++i ) {
magicSquare[i] = new int[dim];
}
while ( 1 ) {
cout << "Please enter the data of the square: " << endl;
for ( int i = 0; i < dim; ++i ) {
for ( int j = 0; j < dim; ++j ) {
cin >> magicSquare[i][j];
}
}
int tempSum = 0;
for ( int i = 0; i < dim; ++i ) {
tempSum += magicSquare[0][i];
}
//row
bool magic = true;
for ( int i = 1; i < dim; ++i ) {
int temp = 0;
for ( int j = 0; j < dim; ++j ) {
temp += magicSquare[i][j];
}
if ( temp != tempSum )
magic = false;
}
if ( !magic ) {
cout << "This is not a magic square." << endl;
break;
}
//column
for ( int i = 0; i < dim; ++i ) {
int temp = 0;
for ( int j = 0; j < dim; ++j ) {
temp += magicSquare[j][i];
}
if ( temp != tempSum )
magic = false;
}
if ( !magic ) {
cout << "This is not a magic square." << endl;
break;
}
//diagonal
int temp = 0;
for ( int i = 0, j = 0; i < dim; ++i, ++j ) {
temp += magicSquare[i][j];
}
if ( temp != tempSum )
magic = false;
if ( !magic ) {
cout << "This is not a magic square." << endl;
break;
}
temp = 0;
for ( int i = 0, j = dim - 1; i < dim; ++i, --j ) {
temp += magicSquare[i][j];
}
if ( temp != tempSum )
magic = false;
if ( !magic ) {
cout << "This is not a magic square." << endl;
break;
} else {
cout << "Yes, this is a magic square." << endl;
break;
}
}
for ( int i = 0; i < dim; ++i )
delete [] magicSquare[i];
delete [] magicSquare;
return 0;
}