I want to ask something because I don't understand something. I want to found min element in array, when I use this code it is fine:
public static int najmanji(int[] niz) {
int min = niz[0];
for (int el = 0; el<niz.length; el++) {
if (niz[el] < min) {
niz[el] = min;
return min;
}
}
return min;
}
But when I use foreach loop I have exception ArrayIndexOutOfBoundsException
.
public static int najmanji(int[] niz) {
int min = niz[0];
for (int el : niz){
if (niz[el] < min) {
niz[el] = min;
return min;
}
}
return min;
}
Why I have this error? Because foreach
is same like for
loop?