forked from tanus786/CP-Codes-HackOctober-Fest-2023
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Magic_square_generator.cpp
74 lines (59 loc) · 1.34 KB
/
Magic_square_generator.cpp
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
/*
* This program constructs a magic square matrix given the dimension as input.
*/
#include <bits\stdc++.h>
using namespace std;
int main()
{
int i, j, n;
cout << "Enter value of n: ";
cin >> n;
int mat[n][n];
for (i = 0; i < n; i++)
{
for (j = 0; j < n; j++)
{
mat[i][j] = 0;
}
}
i = n / 2;
j = n - 1;
for (int num = 1; num <= n * n;)
{
if (i == -1 && j == n)
{
j = n - 2;
i = 0;
}
else
{
if (j == n)
j = 0;
if (i < 0)
i = n - 1;
}
if (mat[i][j])
{
j -= 2;
i++;
continue;
}
else
mat[i][j] = num++;
j++;
i--;
}
printf("The Magic Square for n=%d: \nSum of each row or column %d:\n\n", n, n * (n * n + 1) / 2);
cout << "Sum of each row or column= " << (n * (n * n + 1) / 2);
cout << "\nThe Magic Square for n= " << n << ": \n";
for (i = 0; i < n; i++)
{
for (j = 0; j < n; j++)
{
printf("%3d ", mat[i][j]);
}
cout << endl;
}
return 0;
}
// This code is contributed by Omkar Jahagirdar (Github: omkar3602)