I'm trying to find the minimum value of numbers in an array but it doesn't always work out properly. This is the code I wrote:
for (int i=0; i < arr.length; i++) {
min = arr[i];
for (int j=0; j < arr.length; j++) {
if (arr[j] < arr[0]) {
min = arr[j];
}
}
}
Can someone explain to me what I did wrong and how I can improve the code?
There's no need for the outer loop, it only runs once and you don't use i
anyway. why do you have it?
For the inner loop, you need to compare against the minimum value. Right now you are comparing it against the first element in the array, which is not necessarily the minimum value.
min = arr[0];
for (j=0; j < arr.length; j++) {
if (arr[j] < min) { //<---fix is here
min = arr[j];
}
}
Also you could start the loop at 1, since you don't need to compare arr[0]
against itself (it was just assigned to min
)