C++ programing Procedure- Write a C++ program that prints an n x n magic square
ID: 3670970 • Letter: C
Question
C++ programing
Procedure- Write a C++ program that prints an n x n magic square where the user will specify the value of n. Once the magic square is generated and displayed, use the code from the previous assignment to show the sums of each row, column, and diagonal (using nested for loop to do the math), and display the output to the user.
Program Requirements:
-Use 2D arrays. Both X and Y sizes will be the same (square 2D array). User inputs the SIZE value.
-Error check user input to ensure its odd and within the specified range. You must use a loop for this. You do not need an if/else statement to do this check, and therefore should not for this program.
-Generate the magic square using the algorithm above.
- Output the magic square with the numbers right justified in their columns, and evenly spaced. Make it clean
Sample Output:
This program creates a magic square of a specified size.
The size must be an odd number between 1 and 99.
Enter the size of the magic square: 5
Magic square generated:
Explanation / Answer
#include <stdio.h>
#define NUM 99
void create_magic_square(int n, char magic_square[n][n]);
void print_magic_square(int n, char magic_square[n][n]);
int main(void)
{
int n;
printf("This program creates a magic square of a specified size. ");
printf("The size must be an odd number between 1 and %d. ", NUM);
printf("Enter size of magic square: ");
scanf("%d", &n);
char magic_square[n][n];
create_magic_square(n, magic_square);
print_magic_square(n, magic_square);
return 0;
}
void create_magic_square(int n, char magic_square[n][n])
{
int i, j, num;
for (i = 0; i < n; i++)
for (j = 0; j < n; j++)
magic_square[i][j] = 0;
for (i = 0, j = n / 2, num = 1; num <= n * n; num++) {
if (magic_square[i][j]) {
i = (i + 2) % n;
j = (j - 1 + n) % n;
}
magic_square[i][j] = num;
i = (i - 1 + n) % n;
j = (j + 1) % n;
}
}
void print_magic_square(int n, char magic_square[n][n])
{
int i, j;
for (i = 0; i < n; i++) {
for (j = 0; j < n; j++)
printf("%5d", magic_square[i][j]);
printf(" ");
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.