Confused about how this C code actually works. More specifically, what causes it
ID: 3624666 • Letter: C
Question
Confused about how this C code actually works. More specifically, what causes it to produce the same sum for each row, and column at random? What makes the 1 appear in the middle of the first row?#include<stdio.h>
#include<stdlib.h>
int main()
{
int z[20][20],a,b,aa,bb,d,n;
printf("Please enter an odd number for the dimensions of the square matrix: ");
scanf("%d",&n);
for(a=0;a<n;a++)
for(b=0;b<n;b++)
z[a][b]=0;
a=0;
b=n/2;
for(d=1;d<=n*n;d++)
{
z[a][b]=d;
aa=a++;
bb=b++;
a=(a+1)%n;
b=(b+1)%n;
if(z[a][b]!=0)
{
b=bb;
a=aa-1;
if(a<0)a=n-1;
}
}
Explanation / Answer
the C code that u wrote
just nothing but Generation of ODD MAgic Sqaure
Magic Sqaure is a Sqaure where sum of row column and diaglona will be same.
a=0;
b=n/2;
for(d=1;d<=n*n;d++)
{
z[a][b]=d; // this line causing to put 1 in middle of first row. a = 0 and b = n/2
// middle of first row.
this code using famous algorithm...
go thorough following web pages.
http://user.chollian.net/~brainstm/odd.htm
http://www.markfarrar.co.uk/msqodd01.htm
Related Questions
Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.