+ 2
Doesn't this code should cause index out of bound error?
Java arrays https://code.sololearn.com/cl2srePEGRVi/?ref=app
3 Respostas
+ 3
Of course not.
Because you declared:
for(int i=0;i<ar.length-1;i++)
in the for loop
the length of the array is 5 ar.length-1=5-1=4
So the loop will run until i<4 .
Now in the condition:
if(ar[i]==4||ar[i+1]==4)
{
out+=i;
}
here the highest value of i could be 3 and the highest value of i+1 could be 4
so here the value of ar[3]=4 and ar[4]=5 . Which means the index wasn't out of bound. So it will cause no error. If you give i<ar.length in the for loop it will cause the error.
+ 4
alagammai uma
No because loop will work till 3 < 4 and array has 5 elements so last element index is 4
+ 3