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);
}
}
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.
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++)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With