Computer Science 2 Lab Exercises – 2D Arrays



Comp Sci Lab Exercises – 2D Arrays – “Magic Square”2266950398145A magic square is a square array of numbers consisting of the distinct positive integers 1, 2, ..., arranged such that the sum of the n numbers in any horizontal, vertical, or main diagonal line is always the same number. For example:It is easy to construct a magic square of odd order (that is when n is odd, e.g. 3x3, 5x5, etc.).Method for constructing a magic square of odd order2781300133350The method operates as follows:Starting from the central column of the first row with the number 1, the fundamental movement for filling the squares is diagonally up and right, one step at a time. If a filled square is encountered, one moves vertically down one square instead, then continuing as before. When a move would leave the square (go out of bounds), it is wrapped around to the last row or first column, respectively. (See diagram at right).The code on the back (also on ) will get you started. You just need to write the code to implement the method. Suggestion 1: stay organized, use good variable names, and do one step at a time.Suggestion 2: keep track of your current row and column in two variables. Examine contents of the potential “next” row and column (possibly in 2 different variables) and decide where your next spot will be before switching your current row and column (not necessary, but can make it easier for some people./** * @author (your name) */import java.util.*;public class MagicSquare { public static void main(String[] args) { Scanner s = new Scanner(System.in); System.out.println("Enter size of Magic square (must be odd): "); int n = s.nextInt(); if (n % 2 == 0) throw new RuntimeException("N must be odd"); int[][] magic = new int[n][n]; // YOUR CODE HERE!!!!! // HAVE FUN !!!!! // prints out results will align up to 3 digit #s for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if (magic[i][j] < 10) System.out.print(" "); // extra space for alignment if (magic[i][j] < 100) System.out.print(" "); // extra space for alignment System.out.print(magic[i][j] + " "); } System.out.println(); } }} ................
................

In order to avoid copyright disputes, this page is only a partial summary.

Google Online Preview   Download