A magicsquare is an n x n matrix in which each of the integers 1,2, 3, …, n 2 ap
ID: 3609164 • Letter: A
Question
A magicsquare is an n x n matrix in which each of the integers 1,2, 3, …, n2 appears exactly once and all columnsums, row sums, and diagonal sums are equal. For example, thefollowing is a 5 X 5 magic square in which allrows, columns and diagonals add to 65:
17
24
1
8
15
23
5
7
14
16
4
6
13
20
22
10
12
19
21
3
11
18
25
2
9
The following isa procedure for constructing an n x n magic square for anyodd integer n. Place 1 in the middle of the toprow. Then after integer k has been placed, move up one row and onecolumn to the right to place the next integer k + 1, unless one ofthe following occurs:
(1) If a movetakes you above the top row in the jth column, move to thebottom of the jth column and place k + 1 there.
(2) If a movetakes you outside to the right of the square in the ithrow, place k + 1 in the ith row of the leftmostcolumn.
(3) If a movetakes you to an already filled square or if you move out of thesquare at the upper right-hand corner, place k + 1 immediatelybelow k.
Write a programto construct an n x n magic square for anyodd value of n. You might want to use atwo-dimensional array and allocate memory dynamically. Your programshould have a class to represent magic square.Keep the data members private.Provide your class with accessormethods to set and get the private data. A magicsquare object should be able to construct and displayitself. Write a test program that illustrates the use ofmagic square class and provide output for n = 3,5, and 7.
Include anintroduction, all the code (well documented), screen shot and aconclusion in your report.
17
24
1
8
15
23
5
7
14
16
4
6
13
20
22
10
12
19
21
3
11
18
25
2
9
Explanation / Answer
please rate - thanks import java.util.*; import java.text.*; public class Magicsquare {public static void main(String[] args) {DecimalFormat threedigit = new DecimalFormat("#00 "); String formattednumber; int x=0,y,n,i,j,k=1; Scanner in=new Scanner(System.in); do{ System.out.println("How large isyour square? "); n=in.nextInt(); if(n%2==0) System.out.println("Must be an odd number! - retry"); }while(n%2!=1); int [][]square = new int[n][n]; y=(n+1)/2-1; for(i=0;iRelated Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.