Create a program that will display magic square of numbers based on a given odd magic square size. A magic square is a square array of numbers consisting of the distinct positive integers 1,2, …, arranged such that the sum of the numbers in any horizontal, vertical, or main diagonal line is always the same number, known as the magic constant. The program should ask the user to enter an odd integer that will serve as the size of the square. The program should validate if the entered number is an odd or even number. If the number is even, the program should display an error message and ask the user to enter a number again. Once a valid size is entered, the program should automatically display the magic square.
void magicSquare(int n) {
int x[n][n]; int i, j;
for (i = 0; i < n; i++)
for (j = 0; j < n; j++)
x[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 (x[i][j]) { j -= 2; i++;
continue;
}
else x[i][j] = num++;
j++; i--;
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++)
cout << x[i][j] << ' ';
cout << endl;
}
}
Comments
Leave a comment