Java Number Spiral


 

Java Number Spiral

In this tutorial, you will learn how to create a number spiral.

In this tutorial, you will learn how to create a number spiral.

Java Number Spiral

In this tutorial, you will learn how to create a  number spiral.

A spiral array is a square arrangement of the first N2 natural numbers, where the numbers increase sequentially as you go around the edges of the array. Here, we have created an example, that takes an input from the user which must be a positive odd integer number. And depending on the input value it displays a spiral diagram. The spiral starts with 1 at the center, with 2 to the left, and 3 below it, 4 to the right, and so on.

Example

import java.util.*;
public class NumberSpiral{
public static void main(String[] args) {
Scanner input=new Scanner(System.in);
System.out.print("Enter any integer: ");
int n=input.nextInt();
int sq=n*n;
int i, s = n,x=0, y=0;
int arr [][]= new int [n][n];
i=n*n;
while(i>=1){for(int j=0; j<s; j++)
arr[x][y++] = i--;
x++;
y--;
if(i>=1){for(int j=0; j<s-1; j++)
arr[x++][y] = i--;
x--;
y--;
}
if(i>=1){for(int j=0; j<s-1; j++)
arr[x][y--] = i--;
x--;
y++;
}
if(i>=1){for(int j=0; j<s-2; j++)
arr[x--][y] = i--;
y++;
x++;
s=s-2;
}
}
for(i=0; i<n; i++){
for(int j=0; j<n; j++)
System.out.print(arr[i][j] + " ");
System.out.println();
}
}
}

Output:

Enter any integer: 5
25 24 23 22 21
10 9 8 7 20
11 2 1 6 19
12 3 4 5 18
13 14 15 16 17

Ads