C Program to Solve the Magic Squares Puzzle

C Program to Solve the Magic Squares Puzzle

1092
0
SHARE

The following C program finds the magic square for a given odd sized number, using iteration. A magic square is an arrangement of from 1 to n^2 in an [n x n] , with each number occurring exactly once, and such that the sum of the entries of any row, any column, or any main diagonal is the same.

Here is the source code of the C program to display a linked list in reverse. The C program is successfully compiled and run on a Linux system. The program output is also shown below :

    /*

     * C Program to Solve the Magic Squares Puzzle without using 

     * Recursion

     */

    #include <stdio.h>

     

    void magicsq(int, int [][10]);

     

    int main( )

    {

        int size;

        int a[10][10];

     

        printf("Enter the size: ");

        scanf("%d", &size);

        if (size % 2 == 0)

        {

            printf("Magic square works for an odd numbered size\n");

        }

        else

        {

            magicsq(size, a);

        }

        return 0;

    }

     

    void magicsq(int size, int a[][10])

    {

        int sqr = size * size;

        int i = 0, j = size / 2, k;

     

        for (k = 1; k <= sqr; ++k) 

        {

            a[i][j] = k;

            i--;

            j++;

     

            if (k % size == 0) 

            { 

                i += 2; 

                --j; 

            }

            else 

            {

                if (j == size) 

                {

                    j -= size;

                }

                else if (i < 0)

                {

                    i += size;

                }

            }

        }

        for (i = 0; i < size; i++)

        {

            for (j = 0; j < size; j++)

            {

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

            }

            printf("\n");

        }

        printf("\n");

    }

OUTPUT :

Enter the size: 6
Magic square works for an odd numbered size
 
$ a.out
Enter the size: 5
17  24  1  8  15  
23  5  7  14  16  
4  6  13  20  22  
10  12  19  21  3  
11  18  25  2  9

That’s all guys ! If you have any queries feel free to contact us.

LEAVE A REPLY