CIS 220 - Program 8
Two-dimensional Arrays


Objectives:  Using multi-dimensional arrays, write a program that displays a magic square of whatever size is specified by the user. 

Description:  Magic squares are squares that contain numbers arranged in such a way that all the rows, columns, and diagonals add up to the same number. 


An example of a magic square of size n=3 is shown below. 

 An algorithm exists to determine where numbers should be placed so that rows and columns will add up to the same number.  The algorithm works for odd n only, and is as follows (for a square of size n):

  1. Start with k set to 1 and insert this value in the top center square.

  2. Repeat the following steps until n (or a multiple of n) numbers are in place.

·   Add 1 to k.

·   Move left one square and up one square and insert the number k.  This algorithm assumes that rows and columns wrap-around—if a move is off the top of the square, start again at the bottom; similarly if a move is off the left of the square, start again at the right.

  1. Add one to k.

  2. Move down one square from the last number you placed and insert k.

  3. Go back to step 2 until all squares are filled. 

Write a program to implement this magic square algorithm.  Your program should allow the user to enter the required size (n) in a text field, and then after verifying that n is valid, it should print out a magic square of that size by displaying the n x n array in a text box.  

  • To further check that your magic square is valid, calculate the sum of every row, column, and diagonal, and if they are identical print them in a label titled Sum which is placed below the text box.  If they are not identical, put a ?? in the Sum label.
  • In order to test your checking algorithms, place an invalid value into one of the array elements.
  • Your program should be able to handle any odd value for n between 3 and 9.
  • Use procedures to print the magic square, to check row totals, to check column totals, to check diagonal totals, and for anything else that makes sense.  
  • Error checking is not necessary, other than checking for an odd number between 3 and 9.  
  • Use the "00" format to print.  
  • Be sure to turn in your pseudocode, flowchart, and/or structure chart.

Demo

Clues