Header Ads

Magic square in C

A magic square is a n × n {\displaystyle n\times n} square grid (where n {\displaystyle n} is the number of cells on each side) filled with distinct positive integers in the range 1 , 2 , . . . , n 2 {\displaystyle 1,2,...,n^{2}} such that each cell contains a different integer and the sum of the integers in each row, column and diagonal is equal. The sum is called the magic constant or magic sum of the magic square. A square grid with n {\displaystyle n} cells on each side is said to have order n.
The mathematical study of magic squares typically deals with its construction, classification, and enumeration. Although completely general methods for producing all the magic squares of all orders do not exist, historically three general techniques have been discovered: by bordering method, by making composite magic squares, and by adding two preliminary squares. There are also more specific strategies like the continuous enumeration method that reproduces specific patterns. The magic squares are generally classified according to their order n as: odd if n is odd, evenly even (also referred to as doubly even) if n = 4k (e.g. 4, 8, 12, and so on), oddly even (also known as singly even) if n = 4k + 2 (e.g. 6, 10, 14, and so on). This classification is based on different techniques required to construct odd, evenly even, and oddly even squares. Beside this, depending on further properties, magic squares are also classified as pan-diagonal magic squares and most-perfect magic square. More challengingly, attempts have also been made to classify all the magic squares of a given order as transformations of a smaller set of squares. Except for n ≤ 5, the enumeration of higher order magic squares is still an open challenge. The enumeration of pan-diagonal magic squares of any order was only accomplished in the late 20th century.

************************************Program**************************************
#include<stdio.h>
#include<conio.h>
main()
{
int i,c,n,r;

/* We get the range of matrix in variable n and use
to set the range for magic square box */

printf("Enter the range of magic square\n");
scanf("%d",&n);
int arr[n][n];

/* In first for loop we use to arrange the elements
on the equations of magic square box */


for(i=1;i<=n*n;i++)
{
r=(n-i%n+1+2*((i-1)/n))%n; // for row //
c=((n-1)/2+i-1-(i-1)/n)%n; // for column //
arr[r][c]=i;
}

/* Here we print the generated magic square box using nested for loops */


for(r=0;r<n;r++)
{
for(c=0;c<n;c++)
{
printf("%d\t",arr[r][c]);
}
printf("\n");
}
getch();
}

************************************Output***************************************



1 comment:

  1. hello sir, i wanted to know how you have given the formula for row and column in the first for loop iteration. kindly mail me regarding this info.mailto:rsai48838@gmail.com

    ReplyDelete