Write a Java program to create a spiral array of n * n sizes from a given integer n.
/*
Write a Java program to create a spiral array of n * n sizes from a
given integer n.
Expected Output:
Input a number: 5
Spiral array becomes:
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
*/
import java.util.*;
class Fourteen
{
public static void main(String arg[])
{
Scanner obj = new Scanner(System.in);
int no, a=1, i, j;
System.out.print("\n Enter any number to get spiral array : ");
no = obj.nextInt();
System.out.println();
int arr[][] = new int[no][no];
for (i=0 ; i<=no/2 ; i++)
{
for (j=i; j<no-i ; j++ )
{
arr[i][j] = a;
a++;
}
for(j=i+1 ; j<no-i ; j++)
{
arr[j][no-i-1] = a;
a++;
}
for(j=no-i-2 ; j>=i ; j--)
{
arr[no-i-1][j] = a;
a++;
}
for(j=no-i-2 ; j>i ; j--)
{
arr[j][i] = a;
a++;
}
}
for (i=0 ; i<no ; i++)
{
for (j=0; j<no ; j++ )
{
System.out.print("\t" + arr[i][j]);
}
System.out.println();
}
}
}
More Information on our channel Programmer Community
please like , share and subscribe to get notifications of new videos....
To understand this program video will coming soon on our you tube channel
Comments
Post a Comment