470,850 Members | 1,395 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 470,850 developers. It's quick & easy.

program in c to generate a magic square of size n*n, where n is odd

pls guide me to write a program in c to generate a magic square of size n*n , where n is odd

A magic square is an n*n matrix of integer from 1 to n^2, where n is odd, such that the sum of every row, column and diagonal is same.
The rule is - Start with 1 in the middle of the first row; then go up and left , assigning nos. in increasing order to empty squares; if u fall off the square i.e. if if it is the first column, move to last column in the same row and similarly handle the first row; if the square is occupied, move down instead and continue
Sep 2 '06 #1
1 10264
293 100+
Do you plan on using a 1-D or 2D array?

1. Initialize each array entry to 0. Also, initialize row and column indexes, and a count.
2. Loop from 1 to the total number of array loop entries.
3. For each loop iteration, put your loop variable into the current place in the array. Increment (or decrement) row/column. If the contents of the array is now non-zero, you have been there before, so then adjust the column.

Modular arithmetic is helpful. Suppose you have a 2D array, with int row and int col. Then, to update both of them, do row = (row+N-1)%N and col = (col+N-1)%N to go up one and left one. You could actually make a simple function that does that one small calculation.

The reason why N is added before the modulo operation, %, is because it isn't clear how it acts when it goes into the negative range. That way, N-1 remains positive, and modulo works great.
Sep 2 '06 #2

Post your reply

Sign in to post your reply or Sign up for a free account.

Similar topics

2 posts views Thread by Bruce Lee 646 | last post: by
4 posts views Thread by winnerpl | last post: by
21 posts views Thread by asif929 | last post: by
7 posts views Thread by needhelp20 | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.