Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.Scanner;
- public class Magic {
- public static void main(String[] args) {
- Scanner kb = new Scanner(System.in);
- System.out.println("Enter an odd number greater than 1 and less than 17");
- int size = kb.nextInt();
- int[][] matrix = new int[size][size];
- int r=0;
- int c=size/2;
- int newR = 0;
- int newC = 0;
- matrix[r][c]=1;
- for (int i=2; i<=size*size; i++){
- newR = r-1;
- newC = c+1;
- if (newR<0){
- newR=size-1;
- }
- if (newC > (size-1)){
- newC=0;
- }
- if (matrix[newR][newC]==0){
- matrix[newR][newC]=i;
- r = newR;
- c = newC;
- }
- else {
- matrix[r+1][c]=i;
- r = r+1;
- }
- }
- for ( r=0; r<matrix.length; r++){
- for (c=0; c<matrix[r].length; c++){
- System.out.print(matrix[r][c]+ " ");
- }
- System.out.println();
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement