Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 2

CC 104

Prelim Project
PALOMA, RONA JEAN R.
BSIT-1B
Write a program that will print a magic square in up-left algorithm.

Sample Output:

Enter N: 3

6 1 8
7 5 3
2 9 4

Note: The program will prompt a message if the value inputted for N is even.

Answer:

import java.util.Scanner;

public class Main {

public static void main(String[] args) {

Scanner input = new Scanner(System.in);

System.out.print(“Enter N (odd integer): “);

int n = input.nextInt();

if (n % 2 == 0) {

System.out.println(“N must be an odd integer.”);

return;

int[][] magicSquare = new int[n][n];

int row = 0;

int col = n / 2;

for (int I = 1; I <= n * n; i++) {

magicSquare[row][col] = I;

if (I % n == 0) {

row++;

} else {

if (row == 0) {

row = n – 1;
CC 104
Prelim Project
} else {

row--;

if (col == 0) {

col = n – 1;

} else {

col--;

System.out.println(“Magic Square:”);

for (int I = 0; I < n; i++) {

for (int j = 0; j < n; j++) {

System.out.print(magicSquare[i][j] + “\t”);

System.out.println();

You might also like