Home » Java programs » Java basic programs

Java program to print spiral pattern of the given input



In this java program, we are going to learn how to print a spiral pattern of the numbers, according to the given input.
Submitted by IncludeHelp, on November 30, 2017

Given an input and we have to print spiral pattern using java program.

Example:

    Input: 5
    Output:
    Spiral pattern is:
    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

Program to print spiral pattern in java

import java.util.Scanner;

public class Pattern22
{
	public static void main(String args[])
	{
		// create object.
		Scanner sc = new Scanner(System.in);

		// enter the number of elements.
		System.out.print("Enter the number of elements for pattern : ");
		int n = sc.nextInt();
		
		int A[][] = new int[n][n];
		int k=1, c1=0, c2=n-1, r1=0, r2=n-1;

		while(k<=n*n)
		{
			for(int i=c1;i<=c2;i++)
			{
				A[r1][i]=k++;
			}

			for(int j=r1+1;j<=r2;j++)
			{
				A[j][c2]=k++;
			}

			for(int i=c2-1;i>=c1;i--)
			{
				A[r2][i]=k++;
			}

			for(int j=r2-1;j>=r1+1;j--)
			{
				A[j][c1]=k++;
			}
			
			c1++;
			c2--;
			r1++;
			r2--;
		}

		/* Printing the Spiral pattern */
		System.out.println("The Spiral pattern is : ");
		for(int i=0;i<n;i++)
		{
			for(int j=0;j<n;j++)
			{
				System.out.print(A[i][j]+ "\t");
			}
			System.out.println();
		}
	}
}

Output

First run:
    Enter the number of elements for pattern : 5
    The Spiral pattern is :
    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

Second run:
    Enter the number of elements for pattern : 10
    The Spiral pattern is :
    1	2	3	4	5	6	7	8	9	10
    36	37	38	39	40	41	42	43	44	11
    35	64	65	66	67	68	69	70	45	12
    34	63	84	85	86	87	88	71	46	13
    33	62	83	96	97	98	89	72	47	14
    32	61	82	95	100	99	90	73	48	15
    31	60	81	94	93	92	91	74	49	16
    30	59	80	79	78	77	76	75	50	17
    29	58	57	56	55	54	53	52	51	18
    28	27	26	25	24	23	22	21	20	19





Was this page helpful? YES NO

Are you a blogger? Join our Blogging forum.



Comments and Discussions


We are using Google to publish ads on our website; Google has its own privacy policies. They may save log, cookies on your system. Google may also collect information of your system like IP address, region, city, country. For more details please go through the Google’s privacy policy.