Java Program to Print Spiral Pattern17 Mar 2025 | 5 min read The spiral pattern (or matrix in spiral form) is frequently asked in Java interviews and academics. In this section, we will create a Java program to create a spiral pattern or spiral matrix. What is Spiral Matrix or Spiral Pattern?A spiral pattern is a number pattern that can be represented in matrix form. It is made up of a 2D array (m*n). Pattern may represent in two forms, either clockwise or anticlockwise. In order to print a matrix in spiral pattern (clockwise) form, we need to follow the following traversal order:
In order to print the spiral pattern (anticlockwise), reverse the above traversal order. Let's understand the pictorial representation of the spiral patterns, as shown in the following figure. ![]() For example, consider the following 5*5 matrix: ![]() The above matrix can be represented in spiral form as follows: ![]() We can follow any of the approaches to print the spiral pattern:
Throughout this section, we have used the iterative approach. What should be the approach?
Spiral Pattern Java ProgramSpiralPaternExample1.java Output: ![]() Let's see another spiral pattern. In the following program, we have used the following approach: Starting the indexing from i = 1 and j = 1. It can be observed that every value of the required matrix will be max(abs(i - n), abs(j - n)) + 1. SpiralPatternExample2.java Output: ![]() SpiralPatternExample3.java Output: ![]() Print a Given Matrix in Spiral FormThere are many approaches that can be used to print a matrix in spiral form. SpiralToMatrixExample.java Output: 10 20 30 40 50 60 120 180 170 160 150 140 130 70 80 90 100 110 Next TopicJava Programs |
We request you to subscribe our newsletter for upcoming updates.

We provides tutorials and interview questions of all technology like java tutorial, android, java frameworks
G-13, 2nd Floor, Sec-3, Noida, UP, 201301, India





