+ 1
Can someone explain me this exercise, I still don't understand how it gets to 58.
Int[] myarr = {6, 42, 3, 7}; Int sum=0; For( x=0; x<myArr.length; x++) { Sum+=myArr[x]; } System.out.println(sum) //58
5 Answers
+ 5
Because you for loop is from 0 to 3.
So the sum is myarr[0]+myarr[1]+myarr[2]+myarr[3].
That is your sum is 6+42+3+7.
+ 1
i just guess because x++ so we additional it (6,42,3,7) and 'cause sum += myArr[x] become sum = sum + myArr and the result is 58 (because int sum = 0)
correct me if something wrong đ
0
The array myarr has 4 spots. 0,1,2,3.
in the for loop, X is zero and goes up by one Everytime. it keeps going up as long as it is less than 4, since that is the array length.
so, sum is taking the number in the spot that is equal to X.
first go through, X=0, so sum is equal to the number in the zero slot on the array, being 6.
then it loops again, this time X is in the 1 spot. so sum(6) adds 42 since it's in the 1 spot and you have 48. this goes another 2 times, until X=3.
in this case, it means all numbers are added together to 48.
0
here array.length is 4 .but index is up to 3
0
your array contains 4 elements that is the myarr.length is equal to 4
the condition in for loop iterates it for 4 times from 0 to 3 less than the length of my art
and it's add the value of every element in the array
I.e 6+42+3+7=58