Answer to Question #27147 in C++ for cwojo

Question #27147
A magic square is a square matrix of size n*n where n is an odd integer value, and that each of the integers 1,2,3,... n^2 (that is n squared) appears exactly once. The sum of each column and that of each row as well that of the diagonal must be equal. For example, given a 5*5 magic square, the sum of each row, each column and each diagonal must be equal to 65 and 175 for a 7*7 magic square. Write a program that can be used to accept any odd number as matrix size and output the corresponding magic square.
Expert's answer
#include <stdio.h>
#include <cstdlib>

using namespace std;

int main() {
//freopen ("input.txt", "r", stdin);
//freopen ("output.txt", "w", stdout);
int n;
scanf ("%d", &n);
if (n % 2 == 1) {
& for (int i = 1; i <= n; i++) {
for (int j = 1; j <= n; j++) {
printf ("%d ", 1 + n * ((i + j - 1 + (n - 1) / 2) % n) + (i + 2 * j - 2) % n);
printf ("\n");
& }
} else {
& printf ("Not odd number.\n");
return 0;

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!


No comments. Be first!

Leave a comment

Ask Your question

New on Blog