0
I don't understand the sentence "as the last element's index is myArr.length-1." Why -1 ?
int [ ] myArr = {6, 42, 3, 7}; int sum=0; for(int x=0; x<myArr.length; x++) { sum += myArr[x]; } System.out.println(sum); // 58 The condition of the for loop is x<myArr.length, as the last element's index is myArr.length-1. I don't understand the sentence "as the last element's index is myArr.length-1." Why -1 ? O, 1 , 2 , 3
3 odpowiedzi
+ 5
myArr.length will return 4. But last element's index is Arr[3]. Array indices start from 0. So, last element's index will always be array.length - 1.
+ 3
myArr.length returns the length of the array (4 in this case)
the index of the last element is 3 (because the index start from 0, zero is the first element's index)
so to get the index of the last element you just do:
myArr.length - 1
which gives 3 (4 - 1 = 3)
+ 1
Array's elements numeration starts with zero. So if the size of your array is 4, then the last element will have index 3.
E.g. int [] myArr = { 6, 42, 3, 7 };
myArr[0] = 6
myArr[1] = 42
myArr[2] = 3
myArr[3] = 7 // last element with index 3
myArr.length = 4 // size of array is 4
Please note, that '=' symbol is not an assignment symbol, I've just used it to stamp return values of commands standing left from it