# Thread: Help with magic square program

1. ## Help with magic square program

Hi All,
I am writing a magic square code. I am doing a mistake somewhere because the only value that I can get in the square is the first number. Here is my code and my output. Any help and pointers would be greatly appreciated.Thanks

#include<stdio.h>

#define SIZE 7
#define RANGE SIZE*SIZE

void main(void)
{

int square[SIZE][SIZE]={0};
int count=1;
int col=SIZE/2;
int row=0;
square[row][col]=count;

//build the magic square

do{
count++;
row--;
col++;

if(row == -1 && col == SIZE)
{
row+=2;
col--;
}
else if (row == -1)
row=SIZE-1;
else if(col == SIZE)
col = 0;
else if (square[row][col] != 0)
{
row+=2;
col--;
}
}while (count < RANGE);

//print magic square
for(row=0;row<SIZE;row++){
for(col=0;col<SIZE;col++)
printf("%6d",square[row][col]);
printf("\n");
}
}

output
0 0 0 1 0 0 0
0 0 0 0 0 0 0
0 0 0 0 0 0 0
0 0 0 0 0 0 0
0 0 0 0 0 0 0
0 0 0 0 0 0 0
0 0 0 0 0 0 0 2. Doing

square[row][col] = count;

somewhere in your while loop would be a good idea IMO 3. I got your magic box program to work. Here's the working version
with a couple of comments to show you what I did. I did some reformatting of your source code because it's the only way I could
debug it. Don't take it personally. If this is one of your first programs you have a good start. Try to cut down on the "else if's".

Code:
```#include<stdio.h>

#define SIZE 7
#define RANGE SIZE*SIZE

// changed void main(void) to int main(void)
int main(void)
{

// extra bracketing required here
// see K&R second edition page 111
int square[SIZE][SIZE]={{0}};

int count=1;
int col=SIZE/2;
int row=0;

//build the magic square
do{
count++;
row--;
col++;

if(row == -1 && col == SIZE)
{
row+=2;
col--;
}
else if (row == -1)
row=SIZE-1;
else if(col == SIZE)
col = 0;
else if (square[row][col] != 0)
{
row+=2;
col--;
}

// this line is moved from above
square[row][col] = count;

}while (count < RANGE);

//print magic square
for(row=0;row<SIZE;row++)
{
for(col=0;col<SIZE;col++)
printf("%6d",square[row][col]);
printf("\n");
}
} // end void main(void)``` 4. And just to highlight the obvious in the original code:
>void main(void)
is wrong... main returns an int.

Now this next comment is a personal opinion, so ignore it if you want..... Unreg, I try and avoid using do-while loops that have a lot of code in them. I believe it makes the program harder to read, because until I've read the complete loop, I've no idea what's controlling it. If you think your code must have do-while's, I'd suggest putting a comment at the top of the loop to help the reader see what the controlling factors are. 5. Hi everyone,
Thanks for the help. I got the code to work. Just as a not, the
square[row][col] = count; needs to be a the beginning of the do-while.
I just want to apologize for the lack of comments and the missed up indentation.
Thanks Popular pages Recent additions 