Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

C++ Programming Question: A magic square is an NxN (i.e, square) matrix of numbe

ID: 3829902 • Letter: C

Question

C++ Programming Question:

A magic square is an NxN (i.e, square) matrix of numbers containing all numbers from 1 to N*N such that all the numbers in any given row, column, or main diagonal sum to the same number. The number N is called the order of the square. You can read more about magic squares here (http://en.wikipedia.org/wiki/Magic_square). In this exercise, write a function called generateOddSquare which takes as input a single integer n as the order of the square. If n is an odd number greater than or equal to 3, the function returns a dynamically-allocated n*n-sized linear, integer array which represents a valid magic square when interpreted as a row-major, two-dimensional square array . If n is too small or even the function should return a NULL pointer.

Explanation / Answer

int* generateOddSquare(int n)
{
if (n <3 || n % 2 == 0)
return NULL;
int *magicSquare = (int *)malloc(sizeof(int)*n*n);

// set all slots as 0
memset(magicSquare, 0, sizeof(magicSquare));

// Initialize position for 1
int i = n/2;
int j = n-1;

// One by one put all values in magic square
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 (magicSquare[n*i + j])
{
j -= 2;
i++;
continue;
}
else
magicSquare[n*i + j] = num++; //set number

j++; i--; //1st condition
}


  
return magicSquare;
}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote