+ 22
Can someone please explain this
int arr[] = {1, 3, 2}; int sum = 0; for (int x = 0; x < 4; x++) { sum += arr[x]; } cout << sum << endl;
4 Respostas
+ 8
This snippet speciously intended to gives us the sum of the arr elements, but it violates the boundary of arr, thus, after adding the third element, the last cycle of for loop adds some garbage.value to sum and makes the result invalid.
+ 1
the "for loop" is iterating through your array "arr", by using the index ( i.e the value x, in arr[x] ) of your array, we access each element ( e.g arr[0] == 1 of elements in your array ).
sum +=arr[x], is way we can sum all value of arr[x] into "sum". sum +=arr[x] is similar to sum = sum + arr[x]. but, the condition for exit from the loop is x < 4, arr[3] will be garbage and it will be added to the sum.
I hope this was helpful
+ 1
your loop iterates 4 times on an array with three items. the condition should be x<3 or x<=2
0
arr [3] hold some garbage value. it should be x <3