0
Can someone explain how the sum of an arrays elements works? I know how to write it but it Don't make sense how it works
9 Respuestas
+ 4
int [ ] xyz = {2,3,4};
int sum = 0;
for(int i : xyz) // int i of array xyz
{
sum = sum + i;. /* i takes each value of xyz and adds it to sum */
}
System.out.println(sum);
0
In which language?
0
java
0
It looks like this:
int sum = 0;
for( int i = 0; i< array.length; i++){
sum += array[i];
}
You just add every loop iteration the currently selected element of the array to sum and since sum was zero you get in the end 0+array[0]+array[1]+...
0
so when u declare int sum = 0 u declare it as the index 0 not as a value of 0
0
no I declare sum to have value 0 and than I add the array elements to it one by one. And because the loop goes through all the array elements in the end I have added them all to sum
0
So it initializes sum as zero. Then adds the index 0, 1, 2, 3, and so on till it gets to the last index of the array and adds all the values in the array together and prints the sum of it?
0
It does not add the indexes to sum it adds the values in the array at those indexes, so if your array is [5,3,7] for example it does sum = sum + 5 in the first iteration and since sum is still 0: sum = 0+5=5 then in the second iteration it does sum = sum + 3 and since sum is now 5 it does sum = 5 + 3 and then it does sum = sum + 7 and since sum is now 8 it does sum = 8 + 7 = 15 then the loop ends and sum contains the sum of the values in the array
0
ok I think I'm starting to get it. thank you