C Program to Generate Magic Square

#include<stdio.h>
#include<stdlib.h>

#define SIZE 20

int main()
{
    int order, i, j, k, p, q, mid, magic[SIZE][SIZE];

    printf("Enter order of magic square (order must be odd): ");
    scanf("%d", &order);

    if(order%2==0)
    {
        printf("Order must be odd.\n");
        printf("Exiting...");
        exit(0);
    }

    mid = order/2;

    for(i=0;i< order; i++)
    {
        for(j=0; j< order; j++)
        {
            magic[i][j]=0;
        }
    }

    k=mid;
    j=0;
    for(i=1; i<= order*order; i++)
    {
        magic[j][k] = i;
        p = j--;
        q = k++;

        if(j< 0)
        {
            j = order-1;
        }

        if(k>order-1)
        {
            k=0;
        }

        if(magic[j][k] != 0)
        {
            k = q;
            j = p+1;
        }
    }

    printf("Generated MAGIC SQUARE is:\n");
    for(i=1;i<=6*order;i++)
    {
        printf("-");
    }
    printf("\n");
    for(j=0;j< order;j++)
    {
        printf("|");
        for(k=0; k< order; k++)
        {
            printf("%4d |", magic[j][k]);
        }
        printf("\n");
        for(i=1; i<=6*order; i++)
        {
            printf("-");
        }
        printf("\n");
    }
    return 0;
}

Output

Enter order of magic square (order must be odd): 3
Generated MAGIC SQUARE is:
-----------------------
|   8 |   1 |   6 |
-----------------------
|   3 |   5 |   7 |
-----------------------
|   4 |   9 |   2 |
-----------------------

Leave a Reply

Your email address will not be published. Required fields are marked *

https://atozonlinesolutions.com/wp-content/uploads/2017/03/logo_white.png
https://atozonlinesolutions.com/wp-content/uploads/2017/03/logo_white.png
About
Products
Subscribe

If you wish to receive our latest news in your email box, just subscribe to our newsletter. We won’t spam you, we promise!

    Applauz

    As the pioneer of the lean startup movement, APPLAUZ has dedicated it’s time to sharing effective business strategies that help new businesses and enterpreneurs put their money to work in the right way.

    Subscribe

    If you wish to receive our latest news in your email box, just subscribe to our newsletter. We won’t spam you, we promise!

      Applauz

      As the pioneer of the lean startup movement, APPLAUZ has dedicated it’s time to sharing effective business strategies that help new businesses and enterpreneurs put their money to work in the right way.

      Copyright by BOLD THEMES. All rights reserved.