Java Program to Print Spiral Pattern of Numbers

Last Updated : 7 Aug, 2026

A spiral number pattern is a square matrix in which numbers are arranged in a spiral order. The numbers start from the top-left corner and move right, down, left, and up, repeatedly, until all positions in the matrix are filled.

  • After filling each side, the corresponding boundary moves inward.
  • The process continues until all matrix cells are filled.

Illustration

Input: n = 4

Output:

1 2 3 4
12 13 14 5
11 16 15 6
10 9 8 7

Here, the numbers are filled in the following order:

Right-> Down-> Left-> Up -> Right -> ...... and keep on repeating the same

Approach

To print the spiral pattern:

  • Create an n × n matrix.
  • Start from the top-left cell and place numbers from 1 to n × n.
  • Move in four directions: right, down, left, and up.
  • Change direction whenever the next cell is outside the matrix or has already been filled.
  • Continue until all cells contain a number.
  • Finally, print the matrix row by row.
Java
public class GFG {

    static void printSpiral(int n) {
        int[][] matrix = new int[n][n];

        int top = 0, bottom = n - 1;
        int left = 0, right = n - 1;
        int num = 1;

        while (top <= bottom && left <= right) {

            // Left to right
            for (int col = left; col <= right; col++) {
                matrix[top][col] = num++;
            }
            top++;

            // Top to bottom
            for (int row = top; row <= bottom; row++) {
                matrix[row][right] = num++;
            }
            right--;

            // Right to left
            if (top <= bottom) {
                for (int col = right; col >= left; col--) {
                    matrix[bottom][col] = num++;
                }
                bottom--;
            }

            // Bottom to top
            if (left <= right) {
                for (int row = bottom; row >= top; row--) {
                    matrix[row][left] = num++;
                }
                left++;
            }
        }

        // Print matrix
        for (int row = 0; row < n; row++) {
            for (int col = 0; col < n; col++) {
                System.out.print(matrix[row][col] + " ");
            }
            System.out.println();
        }
    }

    public static void main(String[] args) {
        int n = 4;
        printSpiral(n);
    }
}

Output
1 2 3 4 
12 13 14 5 
11 16 15 6 
10 9 8 7 

Explanation: The program uses four boundaries: top, bottom, left, and right. It fills the matrix in four directions—right, down, left, and up—and moves the corresponding boundary inward after each pass until all cells are filled.

Comment