Skip to content
Advertisement

how to find specific row and column with smallest value 2D array?

so i dont have to find the min value but the specific row and column where the min value is located. This is how much i have that is working haha.

Scanner dati=new Scanner(System.in); 
int[][] a;
int n,m,i,j,z,vertiba,x,v;
vertiba=0;

do{ 
     System.out.print("How many crows (max=20): ");
     n=dati.nextInt();
}while (n<1 || n>20);

do{
     System.out.print("How many columns (max=20): ");
     m=dati.nextInt();;
}while (m<1 || m>20);
     
System.out.print("enter values ");
a=new int[n][m];
      
for( i=0;i< n ; i++){
    for( j=0; j< m; j++) {
        System.out.print("enter values["+i+"]["+j+"] ");
        v= dati.nextInt();
        a[i][j] = v; 
    }
}

for ( i = 0; i < n; i++) {
    for ( j = 0; j < m; j++) {
        System.out.print(a[i][j] + " ");
    }
    System.out.println();
} 
            

Advertisement

Answer

You add something like this to the begining

int min, minCol, minRow;
min = Integer.MAX_VALUE;

Then you extend your input for loop with an if statement

for( i=0;i< n ; i++){
    for( j=0; j< m; j++) {
        System.out.print("enter values["+i+"]["+j+"] ");
        v= dati.nextInt();
        a[i][j] = v; 
        if( v < min ) {
            min = v;
            minRow = i;
            minCol = j;
        }
    }
}
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement