Arrays-Spiral Print Clockwise

able to get output as per program but not sure for wrong answer in testcase

package challenges;

import java.util.Scanner;

public class spiralprint {
static Scanner scan=new Scanner(System.in);
public static void main(String[] args) {

    int   M=scan.nextInt();
	
	int N=scan.nextInt();

	
	if(M<=10&&N<=10)
	{
	int[][] array =displayarray(M,N);
	
	spiralprint(array);
	
	}
}




public static int[][]  displayarray(int rows,int cols)
{
	
	
	
	int [][] array=new int[rows][];
	for(int row=0;row<array.length;row++)
	{
		array[row]=new int[cols];
		
		for(int col=0;col<array[row].length;col++)
		{
			array[row][col]=scan.nextInt();
		}
				
	}


	
	return array;



}

public static void spiralprint(int[][] array)
{

int top=0;
int bottom=array.length-1;
int right=array[top].length-1;
int left=0;
int dir=1;
int count=(right+1)*(bottom+1);



while(left<=right&&top<=bottom)
{
	
	if(count>0)
	{
		if(dir==1)
		{
			
			for(int i=left;i<=right;i++)
			{
				
				System.out.print(array[top][i]+", ");
				count--;
			}
			dir=2;
			top++;
		}

	}
	
	if(count>0)
	{
		
	if(dir==2)
	{
		
	for(int i=top;i<=bottom;i++)
	{
		
		System.out.print(array[i][bottom]+", ");
		count--;
	}
	dir=3;
	right--;
	}
	
	}
	
	if(count>0)
	{
		if(dir==3)
		{
			for(int i=right;i>=left;i--)
			{
				System.out.print(array[bottom][i]+", ");
			count--;
			}
			dir=4;
		bottom--;
		
		}
	}

if(count>0)
{
	if(dir==4)
	{
		for(int i=bottom;i>=top;i--)
		{
			System.out.print(array[i][left]+", ");
			count--;
		}
	}
dir=1;
left++;

}





}



System.out.println("END");

}

}

see you have to add count>0 condition before printing any value…do a dry run for rectangular matrix

did not get you can you elobrate

whenever you are printing something just make a check that count is positive

if(count>0){
//syso
}

I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.

On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.