0

Array

int arr[] = {11, 35, 62, 555, 989}; int sum = 0; for (int x = 0; x < 5; x++) { sum += arr[x]; } //output 1652 int arr[] = {11, 35, 62, 555, 989}; int sum = 0; for (int x = 0; x < 5; x++) { sum = arr[x]; sum++; } //output 990 why not 1656

30th Mar 2017, 3:40 AM
Dipsankar Maity (Cyne)
Dipsankar Maity (Cyne) - avatar
2 Answers
+ 13
sum = value; // assigns value to sum. sum += value; // adds value to sum.
30th Mar 2017, 4:52 AM
Hatsy Rei
Hatsy Rei - avatar
+ 2
sum = arr[x]; This will set the sum equal to value at the index x. So sum is set to 11 then incremented: sum++; So now sum is equal to 12. Then sum is set to arr[ 1 ], which is 35 then incremented to 36. Eventually sum is set to 989 then incremented to 990. I hope that makes sense. Happy coding!
30th Mar 2017, 4:08 AM
Zeke Williams
Zeke Williams - avatar