Answer to Question #278517 in C for Gilleo

Question #278517

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-11T18:45:35-0500
#include <stdio.h>
#include <stdlib.h>
#include <string.h>


int index(int row, int col, int n)
{
    return row*n + col;
}

void build_magic_square(int* a, int n)
{
    int row, col, ind, num;
    row = n/2;
    col = n-1;
    
    for (num=1; num<=n*n; num++) {
        if (a[index(row, col, n)]) {    
            col -= 2;
            row++;
        }
        a[index(row, col, n)] = num;


        row--;
        col++;


        if (row == -1 && col == n) {
            row = 0;
            col = n-2;
        }
        if (row < 0)  row = n-1;
        if (col == n)  col = 0;
    }
}

void print_magic_square(int a[], int n) {
    for (int row=0; row<n; row++) {
        for (int col=0; col<n; col++) {
            printf(" %3d", a[index(row, col, n)]);
        }
        printf("\n");
    }
}

int main() {
    int n=0;
    int* a;

    while (1) {
        printf("Enter an odd number: ");
        scanf("%d", &n);
        if (n>0 && n%2==1)  break;
        printf("n must be positive odd number. Try agin\n\n");
    }

    a = (int *) malloc(sizeof(int)*n*n);
    memset(a, 0, sizeof(int)*n*n);
    build_magic_square(a, n);
    printf("\nMagig Square:\n");
    print_magic_square(a, n);
    free(a);

    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!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS