Last active
March 26, 2017 16:28
-
-
Save Aravin/2c552097029804947d85bbf2a5b4f557 to your computer and use it in GitHub Desktop.
Java program for printing the matrix elements in Spiral Order
This file contains hidden or 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
public static void main(String[] args) { | |
String[][] spiral = new String[3][3]; | |
spiral[0][0] = "1"; | |
spiral[0][1] = "2"; | |
spiral[0][2] = "3"; | |
spiral[1][0] = "4"; | |
spiral[1][1] = "5"; | |
spiral[1][2] = "6"; | |
spiral[2][0] = "7"; | |
spiral[2][1] = "8"; | |
spiral[2][2] = "9"; | |
// Uncomment this section, if you want to get input dynamically. | |
// for(int i=0; i<spiral.length; i++){ | |
// for(int j=0; j<spiral.length; j++){ | |
// Scanner sc = new Scanner(System.in); | |
// sc.next(); | |
// } | |
// } | |
int rowStart, columnStart, rowEnd, columnEnd; | |
rowStart = columnStart = 0; | |
rowEnd = columnEnd = spiral.length - 1; | |
while(rowStart <= rowEnd && columnStart <= columnEnd) | |
{ | |
int i = rowStart, j = columnStart; | |
for(j = columnStart; j<=columnEnd; j++) | |
System.out.println(spiral[i][j]); | |
for(i = rowStart+1, j--; i<=rowEnd; i++) | |
System.out.println(spiral[i][j]); | |
for(j = columnEnd-1, i--; j>=columnStart; j--) | |
System.out.println(spiral[i][j]); | |
for(i = rowEnd-1, j++; i>=rowStart+1; i--) | |
System.out.println(spiral[i][j]); | |
rowStart++; columnStart++; rowEnd--; columnEnd--; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment