Last active
May 15, 2018 08:09
-
-
Save dihardmg/5446659ccb46219b99944104d04cd74a to your computer and use it in GitHub Desktop.
Simple magic square java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package magicsquare; | |
import java.util.Scanner; | |
public class MagicSquare { | |
public static void main(String[] args) { | |
Scanner input = new Scanner(System.in); | |
System.out.print("Input bilangan ganjil: "); | |
int n = input.nextInt(); | |
if (n % 2 == 0) { | |
System.out.println("Harus bilangan ganjil !!!"); | |
System.exit(0); | |
} | |
int square[][] = new int[n + 2][n + 2]; | |
int i = 1, j = (n / 2) + 1; | |
for (int m = 1; m <= Math.pow(n, 2); m++) { | |
square[i][j] = m; | |
if (i - 1 < 1) { | |
i = n; | |
} else { | |
i = i - 1; | |
} | |
if (j + 1 > n) { | |
j = 1; | |
} else { | |
j = j + 1; | |
} | |
if (square[i][j] != 0) { | |
i = i + 1; | |
j = j - 1; | |
if (i > n) { | |
i = 1; | |
} | |
if (j < 1) { | |
j = n; | |
} | |
i++; | |
} | |
} | |
for (int k = 1; k <= n; k++) { | |
for (int l = 1; l <= n; l++) { | |
System.out.print("|" + square[k][l] + ""); | |
} | |
System.out.println("|"); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment