Skip to main content

Spiral Pattern

Draw a spiral pattern using java
spiral
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
package pattern;
import java.util.Scanner;
public class Spiral 
{
 
public static void main(String[] args) 
{
 
	Scanner c=new Scanner(System.in);
	System.out.println("enter a number");
	int b=c.nextInt();
 
	int[][] a=new int[b][b];
	int c1=0,r1=0,c2=b-1,r2=b-1;
	int k=1;
 
	while(k<=b*b)
	{
		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 m=c2-1;m>=c1;m--)
		{
			 a[r2][m]=k++;
		}
		for(int n=r2-1;n>r1;n--)
 
		{
			a[n][c1]=k++;
		}
		c1++;
		c2--;
		r1++;
		r2--;
 
	}
 
    for(int i=0;i<b;i++)
	  {
		for(int j=0;j<b;j++)
		{
			System.out.print(a[i][j]+"     ");	
 
		}
 
		System.out.println();
	  }
 
 
   }
}
 
 
output:
 
enter a number
3
 
1     2     3     
8     9     4     
7     6     5