Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Smallest number in 2d array not working correctly

Tags:

java

arrays

I am trying to find the smallest number in the array.
When i execute this code, it shows "23" as smallest.
I am not able to find the mistake, can anyone help me out?

Here is the code to find the smallest number in 2d array which i tried.
When i execute this code, it shows "23" as smallest.
I am not able to find the mistake.

public class arraymin {
    public static void main(String args[])
    {
        int arr1[][]=new int[][]{{23,32,10,44},{44,33,22,11}};
        int minvalue=arr1[0][0];
        for(int i=0;i<arr1.length;i++)
        {
            for(int j=0;j<arr1.length;j++)
            {
                if(arr1[i][j]<minvalue)
                {
                   minvalue= arr1[i][j];
                }
            } 
        }
        System.out.println("Min Value is: "+minvalue);
    }
}
like image 543
JavaLearner Avatar asked Dec 25 '22 18:12

JavaLearner


2 Answers

You inner loop should be

for(int j=0;j<arr1[i].length;j++)

since the number of columns is different than the number of rows.

And the full code:

public class arraymin {
  public static void main(String args[])
  {
    int arr1[][]=new int[][]{{23,32,10,44},{44,33,22,11}};
    int minvalue=arr1[0][0];
    for(int i=0;i<arr1.length;i++)
    {
        for(int j=0;j<arr1[i].length;j++)
        {
            if(arr1[i][j]<minvalue)
            {
               minvalue= arr1[i][j];
            }
        } 
    }
    System.out.println("Min Value is: "+minvalue);
  }
}

Your current code only checks the first two columns in each row, so out of 23,32,44 and 33, 23 is the smallest number.

like image 58
Eran Avatar answered Dec 27 '22 07:12

Eran


In your inner loop, you use:

for(int j=0;j<arr1.length;j++)

but those arrays are longer, so it will only look at the first two elements of those arrays, making 23 indeed the smallest.

Change the above to:

for (int j = 0; j < arr1[i].length; j++)
like image 21
Stultuske Avatar answered Dec 27 '22 07:12

Stultuske