You can create a clockwise number spiral by filling a two-dimensional array one layer at a time. Start at the top-left corner, move right, down, left, and up, then repeat inside the remaining area. After filling the array, print its rows in order.
Source code
Save this example as NumberSpiralExample.java. It uses a Java 25 compact source file with void main() and the IO console methods. Use JDK 25 or later; no preview flags or external libraries are required. This example introduces arrays and a while loop alongside the for loops used in earlier patterns.
void main() {
int size = 5;
int[][] spiral = new int[size][size];
int top = 0;
int bottom = size - 1;
int left = 0;
int right = size - 1;
int number = 1;
while (top <= bottom && left <= right) {
for (int column = left; column <= right; column++) {
spiral[top][column] = number++;
}
top++;
for (int row = top; row <= bottom; row++) {
spiral[row][right] = number++;
}
right--;
if (top <= bottom) {
for (int column = right; column >= left; column--) {
spiral[bottom][column] = number++;
}
bottom--;
}
if (left <= right) {
for (int row = bottom; row >= top; row--) {
spiral[row][left] = number++;
}
left++;
}
}
int width = String.valueOf(size * size).length();
for (int row = 0; row < size; row++) {
for (int column = 0; column < size; column++) {
if (column > 0) {
IO.print(" ");
}
String value = String.valueOf(spiral[row][column]);
for (int space = value.length(); space < width; space++) {
IO.print(" ");
}
IO.print(value);
}
IO.println();
}
}
Explanation
The declaration int[][] spiral = new int[size][size] creates a square array. Access each position with spiral[row][column]. A size of five gives 25 positions, which the program fills with the integers 1 through 25.
Four variables describe the unfilled area:
| Variable |
Initial value for size 5 |
Meaning |
top |
0 |
First unfilled row |
bottom |
4 |
Last unfilled row |
left |
0 |
First unfilled column |
right |
4 |
Last unfilled column |
The while loop continues as long as the top boundary has not passed the bottom boundary and the left boundary has not passed the right boundary. The logical AND operator, &&, requires both comparisons to be true.
Each iteration fills the available edges in clockwise order:
- Fill the top row from left to right, then increase
top.
- Fill the right column from top to bottom, then decrease
right.
- If a row remains, fill the bottom row from right to left, then decrease
bottom.
- If a column remains, fill the left column from bottom to top, then increase
left.
Updating each boundary before moving to the next edge prevents corners from being filled twice. The two if statements check whether the corresponding boundaries still permit another edge. This matters near the center, where the remaining area may be only one row or one column. The for loop conditions also prevent traversal when their ranges are empty.
The expression number++ uses the current value for the assignment and then increases it by one. For example, spiral[0][0] = number++ stores 1 and leaves number equal to 2.
After the outer layer is complete, the boundaries enclose a smaller area. The next iteration fills that layer, continuing until the array is full. For an odd size, the last layer is a single center position; for an even size, it is a two-by-two layer.
Aligning the output
The array is filled in spiral order but printed in ordinary row order. The two output loops visit every row and column from index zero onward.
String.valueOf(size * size).length() calculates the number of digits in the largest value. For this example, the largest value is 25, so the field width is two characters. A one-digit value receives one leading space, while a two-digit value receives none.
The program also prints one separator space before every column except the first. This keeps the columns readable without adding a separator after the last value. IO.println() ends each row. The IO class belongs to java.lang, so no explicit import is needed.
Run the example
With JDK 25 or later installed, open a terminal in the directory containing the source file and run it directly:
java NumberSpiralExample.java
You can also compile the source file explicitly and then run the compiled program:
javac NumberSpiralExample.java
java NumberSpiralExample
Output
1 2 3 4 5
16 17 18 19 6
15 24 25 20 7
14 23 22 21 8
13 12 11 10 9
Display the output in a monospaced font to preserve column alignment.
Try it yourself
Change size to 4. Trace how the four boundaries move after filling the outer layer, then check the two-by-two inner layer. Compare this with the single center position for size = 5.
Try size = 1, which prints only 1. A size of zero creates an empty array and prints no rows. A negative size causes NegativeArraySizeException when the array is created. Use small positive sizes, such as 3 through 10, for this exercise.
Finally, replace number++ with the constant 1 in all four filling loops. Observe that every position is filled once, even though the traversal changes direction at each edge.