Computer Programming
Math and Arithmetic
C Programming

How do you write the Magic Square program using c?

Answer

User Avatar
Wiki User
06/09/2010

You have to create 9 empty labels on the gui, then randomize 9#'s. assign each random number to the labels in the 3x3 square. ( you have to keep in your head where each random number will be). Then create a loop that does not end until each row, (labels 1-3), each column (labels 1,4,7), and diagnal ( 1,5,9) are different unique numbers and they add to 15(or the magic number).

-----------

For magic squares with an odd number of rows/columns (i.e. 3x3, 5x5, etc.), there is a simple algorithm to fill the squares. Magic squares with even number of rows/columns do NOT follow this algorithm.

Start in the top row, middle square. Place the number 1 there. The rest of the squares are filled as follows.

Choose the next cell by moving up and to the right. If the square falls outside the squares, the next number goes in the first cell of the row above it. If there is no row above it, drop down to the bottom of the next column and place the number there. If there is no column to the right, drop immediately below and place the number there. If the cell is already filled, drop immediately below and place the number there. Continue until all cells are filled. The number in the middle of the sequence should fall in the middle column of the middle row. The formula for the total of each row/column is: total = n * ((( n * n ) / 2 ) + 0.5)

Samples:

Magic square of 3x3:

8 1 6

3 5 7

4 9 2

Each row/column adds up to: 3 * ((( 3 * 3 ) / 2 ) + 0.5) = 15

-----------------------

Magic square of 5x5:

17 24 1 8 15

23 5 7 14 16

4 6 13 20 22

10 12 19 21 3

11 18 25 2 9

Each row/column adds up to: 5 * ((( 5 * 5 ) / 2 ) + 0.5 ) = 65

This algorithm will work for ALL magic squares with an odd number of rows/columns (where number of rows is the same as the number of columns).