Java Program to Print Spiral PatternThe 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
|