// Print an nxn magic square
#include <stdio.h>
int main(void)
{
int n;
printf("This program creates a magic square of a specified size.n");
printf("The size must be an odd number between 1 and 99.n");
printf("Enter size of the square: ");
scanf("%d", &n);
int square[n] [n];
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
square[i] [j] = 0;
}
}
square[0] [n / 2] = 1;
int row = 0, column = n/2;
for (int i = 2; i < n * n + 1; i++) {
if (square[row == 0 ? 4 : row - 1] [(column + 1) % n] == 0) {
square[row == 0 ? row = 4 : --row] [(++column) % n] = i;
} else {
square[++row] [column] = i;
}
for (int j = 0; j < n; j++) {
for (int k = 0; k < n; k++) {
printf("%2d ", square[j] [k]);
}
printf("n");
}
printf("n");
return 0;
}
I’m trying to print a magic square (all rows, columns and diagonals sum to the same number). The way I’m trying to do this is to start by placing 1 in the middle of row 0, and from there assign the next number to the row before one column over (if it exceeds the array bounds it wraps around), if there is already a number there put the next one directly below the number printed before. But for some odd reason when the else clause is executed (the latter happens), it assigns i to the wrong row. After some time trying to figure out what happened I decided to print the row together with the assignment and remove the increment to see what would happen:
} else {
square[printf("row: %d ", row), row] [column] = i;
}
Row prints as 1 and it keeps assigning the value to row 2.:
screenshot
sorry if this is unclear, I’m new to programming.
user26044236 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.