Magic Square Generator By C Programming
Magic Square is a kind Of Square where the Summation of numbers in each row, and in each column, and the Sum of the numbers in the diagonal Will be Same. See This Picture3×3 Magic Square |
If Our Dimension is n then Total Numbers Will be n×n. Now We Will Create An Odd Dimensional
Magic Square Generator Like 3×3, 5×5 etc. Using C Programming.
At First The Loop will be Started From 1 and will be continued Till n×n. This Loop Will set The Place Value Of The numbers From 1 to n×n. Example: At first when i=1 in Magic Square
Place Of 1 Will be Just Middle Of First Row. See this Picture
Suppose We will generate 3×3 Magic Square. Then Row Position Of 1 will be 0 And Collum
Position Of 1 Will be 1 And That is m[0][1]. Here Two Dimensional Array is m[3][3]. We will get The Value Of Row And Collumn Applying A Rule. Suppose Row Position Variable
is a And Collumn Position Variable Is b. Then Position Of 1 Will be
int m[n][n];
for(i=1;i<=(n*n);i++)
{
a=(n-i%n+1+2*((i-1)/n))%n;
b=((n-1)/2+i-1-(i-1)/n)%n;
b=((n-1)/2+i-1-(i-1)/n)%n;
m[a][b]=i;
}
Here n=3 (dimension), i=1 (first loop value)
When i=1, n=3 a is a=0 and b is b=1. So The Position Of 1 is m[0][1]=1
Then i=2, n=3 a will be a=2 and b will be b=2. So The Position Of 2 will be m[2][2]=2
Every value Till n×n will be Set Like This Rule And Finally We will be Able to Create A
Magic Square Generator. Here is The Full Code
#include <stdio.h>
int main()
{
int n,i,a,b;
printf("Enter Odd Dimension number=");
scanf("%d",&n);
while(1)
{
if((n%2==0||n>=25))
{
printf("Please Enter The Odd Dimension number (Ex:3 or 5 or 7..):");
scanf("%d",&n);
}
else
break;
}
int m[n][n];
for(i=1;i<=(n*n);i++)
{
a=(n-i%n+1+2*((i-1)/n))%n;
b=((n-1)/2+i-1-(i-1)/n)%n;
m[a][b]=i;
}
for(a=0;a<n;a++)
{
for(b=0;b<n;b++)
{
printf("%d\t",m[a][b]);
}
printf("\n");
}
return 0;
}
int main()
{
int n,i,a,b;
printf("Enter Odd Dimension number=");
scanf("%d",&n);
while(1)
{
if((n%2==0||n>=25))
{
printf("Please Enter The Odd Dimension number (Ex:3 or 5 or 7..):");
scanf("%d",&n);
}
else
break;
}
int m[n][n];
for(i=1;i<=(n*n);i++)
{
a=(n-i%n+1+2*((i-1)/n))%n;
b=((n-1)/2+i-1-(i-1)/n)%n;
m[a][b]=i;
}
for(a=0;a<n;a++)
{
for(b=0;b<n;b++)
{
printf("%d\t",m[a][b]);
}
printf("\n");
}
return 0;
}
0 comments:
Post a Comment