The world’s Largest Sharp Brain Virtual Experts Marketplace Just a click Away
Levels Tought:
Elementary,Middle School,High School,College,University,PHD
| Teaching Since: | Apr 2017 |
| Last Sign in: | 103 Weeks Ago, 2 Days Ago |
| Questions Answered: | 4870 |
| Tutorials Posted: | 4863 |
MBA IT, Mater in Science and Technology
Devry
Jul-1996 - Jul-2000
Professor
Devry University
Mar-2010 - Oct-2016
A magic square of order n is an arrangement of integers 1 through n2Â in a square format such that the sum of numbers along any row, any column and any diagonal is the same. Your program inputs an odd integer n (< 50), and prints a magic square of order n.Â
The following algorithm holds good only for an odd n. Assume n is an odd integer.Â
Call the rectangular array magicSquare[][], and initialize all elements of the array to 0. Start by keeping 1 in the middle cell of row 0. That is, K = 1, I = 0, J = n/2 and magicSquare[I][J] = K.Â
Once K is placed in a cell, do K++. Place the new K in the "north east" cell. In other words, after placing a K in a cell, do K++, I--, J++, and place the new K at the cell (I,J).Â
| There are four situations you cannot place the new K in the new cell: Situation | Solution |
| The new (I,J) is out of bounds in the Northern direction i.e. I < 0. | Wrap around and go to the last row, but in the same column. i.e. I = n-1. |
| The new (I,J) is out of bounds in the Eastern direction. i.e. J > n-1. | Wrap around and go to column 0, but in the same row. i.e. J = 0. |
| The new (I,J) is out of bounds in both directions (happens only once). i.e. I < 0 and J> n-1. | Go one row below from the original position (before you did I-- and J++), in the same column. i.e. I +=2, J--. |
| The new (I,J) position in the array is already taken by an earlier K. i.e. magic_square[I][J] != 0. | Go one row below from the original position (before you did I-- and J++), in the same column. i.e. I +=2, J--. |
Continue this process until all the numbers 1 - n2 (n squared) are placedÂ