I am trying to print the elements in the anti-clock direction in the spiral form.
but I am getting an element missing in the format.
eg:
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
starting from 4, Instead of the actual output : 4 3 2 1 5 9 13 14 15 16 12 8 7 6 10 11
I am getting : 4 3 2 1 5 9 13 14 15 16 8 7 6 10 11
Also, can anyone give me an Optimized solution if you have
Here is my code:
public class Sprial_Matrix {
public static void main(String args[]) {
Scanner s = new Scanner(System.in);
int m=4;
int n=4;
System.out.println("Elements: ");
int arr[][] = new int[m][n];
for(int i=0;i<m;i++) {
for(int j=0;j<n;j++) {
arr[i][j]=s.nextInt();
}
}
int k=0,l=0;
while(k<m && l<n) {
for(int i=n-1;i>=l;i--) {
System.out.print(arr[k][i]+" ");
}
k++;
for(int i=k;i<m;i++ ) {
System.out.print(arr[i][l]+" ");
}
l++;
if(k<m) {
for(int i=l;i<=m-1;i++)
System.out.print(arr[m-1][i]+" ");
}
m--;
}
if(l<n) {
for(int i=m-1;i>=l;i--) {
System.out.print(arr[i][n-1]+" ");
}
n--;
}
s.close();
}
}
Appreciate the feedback that you give and thanks,,,
The problem is caused by a poor formatting of your code. If you format the code with correct indents then you'll see that the last if
statement is actually outside the while
loop:
if(k<m) {
for(int i=l;i<=m-1;i++) // There is no { on this line!
System.out.print(arr[m-1][i]+" ");
} // So this } closes the 'if', not 'for'
m--;
} // And this } closes the 'while', not 'if'
if(l<n) { // So this 'if' is outside the loop.
for(int i=m-1;i>=l;i--) {
System.out.print(arr[i][n-1]+" ");
}
n--;
}
Simple fix is to do the following:
if(k<m) {
for(int i=l;i<=m-1;i++) { // FIX: added {
System.out.print(arr[m-1][i]+" ");
}
m--;
}
if(l<n) {
for(int i=m-1;i>=l;i--) {
System.out.print(arr[i][n-1]+" ");
}
n--;
}
} // FIX: added }
Better solution would be to use better formatting of the whole program. Also, your class has a typo in its name, Sprial, not Spiral.