Can someone explain me this exercise, I still don't understand how it gets to 58. | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 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

6th Apr 2016, 7:45 PM
Michel
Michel - avatar
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.
20th Apr 2016, 11:09 AM
許應安
許應安 - avatar
+ 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 😅
17th May 2016, 6:56 AM
Alexander
Alexander - avatar
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.
24th Jun 2016, 4:15 AM
Bobby Turnip (Scye)
Bobby Turnip (Scye) - avatar
0
here array.length is 4 .but index is up to 3
14th Sep 2016, 4:04 PM
ESWAR
ESWAR - avatar
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
28th Nov 2016, 7:31 AM
Prabhat Rai
Prabhat Rai - avatar