Answer to Question #278521 in C for Gilleo

Question #278521

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.



1
Expert's answer
2021-12-12T01:17:35-0500
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;
  }
}

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!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS