+ 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;

21st Apr 2017, 7:38 PM
Joseph Sai
Joseph Sai - avatar
4 odpowiedzi
+ 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.
21st Apr 2017, 7:48 PM
Babak
Babak - avatar
+ 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
22nd Apr 2017, 10:02 PM
eric mensah
eric mensah - avatar
+ 1
your loop iterates 4 times on an array with three items. the condition should be x<3 or x<=2
25th Apr 2017, 10:13 AM
Wilson sfiso
Wilson sfiso - avatar
0
arr [3] hold some garbage value. it should be x <3
24th Apr 2017, 9:51 AM
Padmanabhan