+ 8
java arrays
How its can be possible 58? Can you explain for me please? Can you explain to me array's logic? 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
9 Respostas
+ 2
Can someone explain to me how to retrieve the number of elements of an array?
+ 1
Hmm you just sum all of the elements in your "myArr".
for x=0: 0+6=6
for x=1: 6+42= 48
for x=2: 48+3=51
for x=3: 51+7=58
The length of your array is 4 so you are counting from 0 to 3. Finish
0
you loop over your array.
loop# |x |myArr[x] |sum
1. |0 | 6 |6
2. |1 |42 |6 + 42 = 48
3. |2 | 3 |48+ 3 = 51
4. |3 | 7 |51 + 7 = 58
0
Thank you
0
thanks
0
more
0
thanks!!!
I understood well after this example.
0
Thank you. Now I understand
0
Gabriellah Palawo arrays have the length property which provides the length or capacity of the array. It gives the total space allocated during the initialisation of the array. Here's an example:
// creating a new array of 5 elements
int arr[] = new int[5];
// store some elements to the array
arr[0] = 2;
arr[1] = 4;
// print length of array
System.out.println(arr.length); //5
Calling the length element of the array arr[] will return 5.