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

[20 points] An nx n magic square, where n is odd and between 1 and 99, is an arr

ID: 3757564 • Letter: #

Question

[20 points] An nx n magic square, where n is odd and between 1 and 99, is an arrangement of numbers 1, 2, 3, .., n in such a way that sum of rows, columns, and diagonals are all the same. The scheme to create a magic square is as follows: A. Start by placing 1 n the middle of row O. Place each of the remaining numbers 2, 3,... n?. by moving one row up and shifting one column over. Any attempt to go outside the bounds of the array should "wrap around" to the opposite side of the array. If a cell is already occupied, put the number directly below the previously stored number. For example, a magic square with n 3 and n- 5 look like: 17 24 1 815 235714 16 46132022 4 9 2 10 12 19213 n 3 (magic value 15) 11 18 252S9 n 5 (magic value 65) Write a C-program that accepts the value of n as command line argument and displays the magic square in a row-column format (something similar to above). You can assume the user restricts n between 1 and 15. Also, indicate the sum value (the magic value) of the square. If the use enters an even number, or a number outside the valid range (1-15), then the program should indicate that with appropriate message.

Explanation / Answer

#include<stdio.h>

#include<string.h>

  

//method to genrate magic square

void MagicSquare(int n)

{

int tempSquare[n][n];

int i,j;

//setting vall values to 0

for(i=0;i<n;i++)for(j=0;j<n;j++)tempSquare[i][j]=0;

  

  

i = n/2;

j = n-1;

  

  

//setting 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 (tempSquare[i][j])

{

j -= 2;

i++;

continue;

}

else

tempSquare[i][j] = num++;

  

j++; i--;

}

  

//displaying magic square:

printf("Magic Square for n : %d: sum of each row or column or diagonal :%d ", n, n*(n*n+1)/2);

for (i=n-1; i>-1; i--)

{

for (j=n-1; j> -1; j--)

printf("%3d ", tempSquare[j][i]);

printf(" ");

}

}

  

//testing

int main()

{

int n;

//reading input

printf("Enter a odd number(between 1-15 inclusive):");

scanf("%d",&n);

if(15<n || n<1)

{

printf("Error : number shoud be between 1-15 inclusive ");

}

else if(n%2 ==0) printf("Error : number shoud be odd ");

else //calling method

MagicSquare (n);

return 0;

}

output:

Enter a odd number(between 1-15 inclusive):3
Magic Square for n : 3:
sum of each row or column or diagonal :15

8 1 6
3 5 7
4 9 2


Process exited normally.
Press any key to continue . . .

//

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