LAB 11  (Comp 170)

Two-Dimensional Arrays:  Magic Squares

In today's lab, we will study the magic square problem as described in problem 5 on page 288 of Kamin-Mickunas-Reingold.

A magic square is an n x n grid of the integers 1 through n2 that sum to the same value across rows, down columns, and along the two diagonals.  For example:
 
8 1 6
3 5 7
4 9 2

An old method for constructing magic squares of odd order was devised by de la Loubere.  It involves placing the "next" number of the magic square diagonally up and to the right of the previous number, with the following warnings:

(a)  One row "up" from the top row lands you in the bottom row.
(b)  One column "right" from the rightmost column lands you in the leftmost column.
(c)  If the desired cell is already occupied, then instead place the next number below the previous one.
(d)  Begin by placing the number 1 in the middle of the top row.

Write a Java application that reads an odd positive integer and displays an n x n magic square.
 
 
 

 Course Home Page            Department Home Page          Loyola Home Page