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

2. A magic square is a square array of numbers where the sum of the numbers acro

ID: 664542 • Letter: 2

Question

2. A magic square is a square array of numbers where the sum of the numbers across each row, down each column, or along either of the main diagonals is the same. For example: Here is an algorithm for creating a (2n - 1) x (2n - 1) magic square: we begin by entering 1 at the top-left comer and moving diagonally down and to the right by one square at each step that we can, wrapping around the edges of the board as needed. When we reach a filled-in square, we move down by two squares and then return to the diagonal moves. At the end of the process, we reset the entire square so that the middle square holds the average value. The two squares above were

Explanation / Answer

C code to generate Magic Square

#include<stdio.h>
#include<string.h>

void generateSquare(int n)
{
    int magicSquare[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) //3rd condition
        {
            j = n-2;
            i = 0;
        }
        else
        {
          
            if (j == n)
                j = 0;
          
            if (i < 0)
                i=n-1;
        }
        if (magicSquare[i][j]) //2nd condition
        {
            j -= 2;
            i++;
            continue;
        }
        else
            magicSquare[i][j] = num++; //set number

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


    // print magic square
    printf("The Magic Square for n=%d: Sum of each row or column %d: ",
            n, n*(n*n+1)/2);
    for(i=0; i<n; i++)
    {
        for(j=0; j<n; j++)
            printf("%3d ", magicSquare[i][j]);
        printf(" ");
    }
}

int main()
{
    int n = 3;
    generateSquare (n);
    n=5;
    generateSquare (n);
    return 0;
}

a) As evident from the algorithm used it will fill up the evert space from 1 to(2n-1)2  

b) Same as above. check the algorithm.