CPSC 170 Lab 3: Two Dimensional Arrays

As usual, create a lab3 subdirectory for today's lab, open this document in Netscape, and start emacs.

Non-Rectangular Arrays

We usually think of a two dimensional array as a table or matrix, but in Java it is also possible to create non-rectangular two dimensional arrays. There are two ways to do this:

File TwoD.java contains a shell for a program that reads in and prints out information about variable sized groups of people. This information will be stored in a two dimensional array, with each row representing one group. The program should ask the user for the number of groups and use this information to create the appropriate number of rows in the array. For each group it should then ask how many people are in the group and use this information to make that row of the array just the right length. It should then ask for the names for that group and store them in the array. After all the data has been entered, the names in each group should be listed. For example, a run of your program might look like this;

Enter number of groups: 3

Enter number of people in group 0: 2
Name 0: rachel
Name 1: elly

Enter number of people in group 1: 3
Name 0: spud
Name 1: madison
Name 2: floyd

Enter number of people in group 2: 1
Name 0: beauty

** GROUP SUMMARY **
GROUP 0: rachel elly 
GROUP 1: spud madison floyd 
GROUP 2: beauty 
In testing your program, try a group of size 0 (among others) to see what happens.

Print your program to turn in.

Magic Squares

One interesting application of two dimensional arrays is magic squares. A magic square is a square matrix in which the sum of every row, every column, and both diagonals is the same. Magic squares have been studied for many years, and there are some particularly famous magic squares. In this exercise you will write code to determine whether a square is magic.

File Square.java contains the shell for a class that represents a square matrix. It contains headers for a constructor that gives the size of the square and methods to read values into the square, print the square, find the sum of a given row, find the sum of a given column, find the sum of the main (or other) diagonal, and determine whether the square is magic. The read method is given for you; you will need to write the others.

File SquareTest.java contains the shell for a program that reads input for squares and tells whether each is a magic square. Following the comments, fill in the remaining code. Run your program on file magicData (you'll need to redirect the input to do this: java SquareTest < magicData) -- you should find that the first, second, and third squares in the input are magic, and that the rest (fourth through seventh) are not. Note that the -1 at the bottom tells the test program to stop reading.

HAND IN: