Doesn't this code should cause index out of bound error? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 2

Doesn't this code should cause index out of bound error?

Java arrays https://code.sololearn.com/cl2srePEGRVi/?ref=app

22nd Jun 2021, 6:42 AM
alagammai uma
alagammai uma - avatar
3 Answers
+ 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.
22nd Jun 2021, 6:58 AM
The future is now thanks to science
The future is now thanks to science - avatar
+ 4
alagammai uma No because loop will work till 3 < 4 and array has 5 elements so last element index is 4
22nd Jun 2021, 6:56 AM
A͢J
A͢J - avatar