Magic Square preferred output

417 views Asked by At

I have an assignment about MAGIC SQUARE:

But i need to rewrite it.

This is my code at the moment:

    Scanner input = new Scanner(System.in);

    System.out.print("Enter a number: ");
    int num= input.nextInt();

    //Number must be ODD and not less than or equals to one to continue 
    while((num%2==0)||(num<=1)){
        System.out.println("Enter a valid number: ");
        num= input.nextInt();
    }



    int[][] magic = new int[num][num];

    int row = num-1;
    int col = num/2;
    magic[row][col] = 1;

    for (int i = 2; i <= num*num; i++) {
        if (magic[(row + 1) % num][(col + 1) % num] == 0) {
            row = (row + 1) % num;
            col = (col + 1) % num;
        }
        else {
            row = (row - 1 + num) % num;
            // don't change col
        }
        magic[row][col] = i;
    }

    // print results
    for (int i = 0; i < num; i++) {
        for (int j = 0; j < num; j++) {
            if (magic[i][j] < 10)  System.out.print(" ");  // for alignment
            if (magic[i][j] < 100) System.out.print(" ");  // for alignment
            System.out.print(magic[i][j] + " ");
        }
        System.out.println();
    }


Currently, my program output is:

My Program output

My expected/desired output:

enter image description here

What I need is for the starting number (1) to be in the upper middle of the row x col then the pattern is up then left.

1

There are 1 answers

1
santosh-patil On

If the starting number should be the upper element is the only condition you are missing then iterating the print result row loop in reverse order will solve the problem. So instead of printing rows in order 0, 1, 2, ..., n, try to print rows in order n, n-1, n-2, ..., 1, 0. Apply same logic to columns to get the output same as the goal output.