Hi I m going to teach you how to print array elements in spiral order in a double dimensional array.This logic will be helpful in various other programs of this category.
compile the code either by CMD or by other emulator.
Ex-Input
1 2 3 4
5 6 7 8
9 10 11 12
Output-
1 2 3 4 8 12 11 10 9 5 6 7
compile the code either by CMD or by other emulator.
Ex-Input
1 2 3 4
5 6 7 8
9 10 11 12
Output-
1 2 3 4 8 12 11 10 9 5 6 7
Code:-
import java.io.*;
class spiral
{
public static void main(String args[])throws IOException
{
BufferedReader in=new BufferedReader(new InputStreamReader(System.in));
int m,n;
m=Integer.parseInt(in.readLine());
n=Integer.parseInt(in.readLine());
int mu[][]=new int[m][n];
int val,row,coln,x,y,z,j,lst;
for(int i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
mu[i][j]=Integer.parseInt(in.readLine());
}
}
for(int i=0;i<m;i++)
{
for( j=0;j<n;j++)
{
System.out.print(+mu[i][j]);
}
System.out.println();
}
for(j=0;j<n;j++)
{
System.out.print(" "+mu[0][j]);
}lst=n-1;
for(x=1;x<m*n;x++)
{ m--;
n--;
for(coln=1;coln<=m;coln++)
{
if(x%2!=0)
lst=lst+10;
else
lst=lst-10;
y=lst%10;
z=lst/10;
System.out.print(" "+mu[z][y]);
}
for(row=1;row<=n;row++)
{
if(x%2!=0)
lst=lst-1;
else
lst=lst+1;
y=lst%10;
z=lst/10;
System.out.print(" "+mu[z][y]);
}
}
}
}