Created
February 21, 2012 20:26
-
-
Save gnarula/1878684 to your computer and use it in GitHub Desktop.
The program displays first n*n natural numbers arranged in clockwise spiral in n*n array
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* The program displays first n*n natural numbers arranged in clockwise spiral in n*n array | |
* | |
* Example: | |
* | |
* for n = 3; output | |
* | |
* 1 2 3 | |
* 8 9 4 | |
* 7 6 5 | |
* | |
* Note: formatting for double digits isn't looked into | |
* | |
* @author Gaurav Narula | |
* | |
* */ | |
public class spiral { | |
private int[][] arr; | |
private int n; | |
public spiral(int n) { | |
this.n = n; | |
arr = new int[n][n]; | |
} | |
public void magic() { | |
int temp = n; | |
int k = 0; | |
int last = 0; | |
int count = 0; | |
while(count < n*n) { | |
// fill the upper horizontal row | |
for(int i = k; i < temp && count != n*n; i++, last++) { | |
arr[k][i] = last + 1; | |
count++; | |
} | |
// fill the right column | |
for(int i = k; i < temp - 1 && count != n*n; i++, last++) { | |
arr[i+1][temp-1] = last + 1; | |
count++; | |
} | |
// fill lower horizontal row | |
for(int i = temp - 2; i >= k && count != n*n; i--, last++) { | |
arr[temp-1][i] = last + 1; | |
count++; | |
} | |
// fill left column | |
for(int i = temp - 2; i > k && count != n*n; i--, last++) { | |
arr[i][k] = last + 1; | |
count++; | |
} | |
temp -= 1; | |
k++; | |
} | |
} | |
public void display() { | |
for(int i = 0; i < n; i++) { | |
for(int j = 0; j < n; j++) | |
System.out.print(arr[i][j] + " "); | |
System.out.println(); | |
} | |
} | |
public static void main(String[] args) { | |
spiral ob = new spiral(7); | |
ob.magic(); | |
ob.display(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment