Open In App

Java Program to Print Spiral Pattern of Numbers

Last Updated : 12 Sep, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

Given a number n as the size of the matrix, the task is to print a spiral pattern of size n.

Examples:

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

Preview of the Spiral Pattern:

Lightbox 

Java




public class GFG {
 
    public static void printSpiral(int size)
    {
 
        // Create row and col
        // to traverse rows and columns
        int row = 0, col = 0;
 
        int boundary = size - 1;
        int sizeLeft = size - 1;
        int flag = 1;
 
        // Variable to determine the movement
        // r = right, l = left, d = down, u = upper
        char move = 'r';
 
        // Array for matrix
        int matrix[][] = new int[size][size];
 
        for (int i = 1; i < size * size + 1; i++) {
 
            // Assign the value
            matrix[row][col] = i;
 
            // switch-case to determine the next index
            switch (move) {
 
            // If right, go right
            case 'r':
                col += 1;
                break;
 
            // if left, go left
            case 'l':
                col -= 1;
                break;
 
            // if up, go up
            case 'u':
                row -= 1;
                break;
 
            // if down, go down
            case 'd':
                row += 1;
                break;
            }
 
            // Check if the matrix
            // has reached array boundary
            if (i == boundary) {
 
                // Add the left size for the next boundary
                boundary += sizeLeft;
 
                // If 2 rotations has been made,
                // decrease the size left by 1
                if (flag != 2) {
 
                    flag = 2;
                }
                else {
 
                    flag = 1;
                    sizeLeft -= 1;
                }
 
                // switch-case to rotate the movement
                switch (move) {
 
                // if right, rotate to down
                case 'r':
                    move = 'd';
                    break;
 
                // if down, rotate to left
                case 'd':
                    move = 'l';
                    break;
 
                // if left, rotate to up
                case 'l':
                    move = 'u';
                    break;
 
                // if up, rotate to right
                case 'u':
                    move = 'r';
                    break;
                }
            }
        }
 
        // Print the matrix
        for (row = 0; row < size; row++) {
            for (col = 0; col < size; col++) {
 
                int n = matrix[row][col];
                System.out.print((n < 10) ? (n + " ")
                                          : (n + " "));
            }
 
            System.out.println();
        }
    }
 
    // Driver Code
    public static void main(String[] args)
    {
 
        // Get the size of size
        int size = 5;
 
        // Print the Spiral Pattern
        printSpiral(size);
    }
}


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 

Time complexity: O(n*n) where n is given size of matrix

Auxiliary space : O(n*n) for 2-d matrix



Next Article
Article Tags :
Practice Tags :

Similar Reads

Java Program to Print Left Triangle Star Pattern
In this article, we will learn about printing Left Triangle Star Pattern. Examples: Input : n = 5 Output: * * * * * * * * * * * * * * * Left Triangle Star Pattern: Java Co...
15+ min read
Java Program to Print Star Pascal’s Triangle
Pascal’s triangle is a triangular array of the binomial coefficients. Write a function that takes an integer value n as input and prints the first n lines of Pascal’s tria...
9 min read
Java Program to Convert Binary to Octal
A Binary (base 2) number is given, and our task is to convert it into an Octal (base 8) number. There are different ways to convert binary to decimal, which we will discus...
15 min read
Java Program to Find Factorial of a Number Recursively
Factorial of a number n is defined as a product of all positive descending integers, Factorial of n is denoted by n!. Factorial can be calculated using the following recur...
13 min read
Java Program to Print Pyramid Number Pattern
Here we are getting a step ahead in printing patterns as in generic we usually play with columnar printing in the specific row keep around where elements in a row are eith...
2 min read
Java Program to Print matrix in snake pattern
Given an n x n matrix .In the given matrix, you have to print the elements of the matrix in the snake pattern. Examples : Input :mat[][] = { {10, 20, 30, 40}, {15, 25, 35,...
1 min read
Java Program to Print Square Star Pattern
Here, we will implement a Java program to print the square star pattern. We will print the square star pattern with diagonals and without diagonals. Example: *************...
2 min read
Java Program to Print Pyramid Star Pattern
This article will guide you through the process of printing a Pyramid star pattern in Java. 1. Simple pyramid pattern Java Code import java.io.*; // Java code to demonstra...
2 min read
Program to print numbers with diamond pattern
write a program where each column represents same number according to given example:Examples : Input : 5 Output : 1 212 32123 212 1 Input : 7 Output : 1 212 32123 4321234...
1 min read
Java Program to Print Mirror Lower Star Triangle Pattern
In this article, we are going to learn how to print mirror lower star triangle patterns in Java. Illustration: Input: number = 7 Output: * * * * * * * * * * * * * * * * *...
2 min read