0

I don't get the point of increment in this code please explain.

#include <iostream> using namespace std; int main() { int arr[] = {11, 35, 62, 555, 989}; int sum = 0; for (int x = 0; x < 5; x++) { sum += arr[x]; } cout << sum << endl; return 0; }

10th Aug 2016, 7:16 AM
Sundus Yawar
Sundus Yawar - avatar
3 Respostas
0
There's is none. It's just an example to demonstrate working of array.
10th Aug 2016, 7:39 AM
Nick D.
Nick D. - avatar
0
sum=sum + arr [i] now initially sum is 0 and after that it adds all the element of arr by increasing the value of i to access its all elements.
10th Aug 2016, 7:57 AM
Tarun kumar parashar
Tarun kumar parashar - avatar
0
In the for loop, it starts by calling the integer in the array in slot 0 (arr[0] = 11). It then does the sum += arr[x] arithmetic (sum = sum + 11 which is 0+11=11) Remember, sum initially = 0. It then moves to the next x value (1), so it pulls the integer in the array in the 1 slot (arr[1] = 35). Again it evaluates the sum += arr[x] again (sum = sum + 35 which is 11 + 35 = 46). So in the first iteration, sum = 11. In this second iteration sum now = 46 after all the code is run. And so on... So in this code, variable x is the value that is used to go through the for loop and when to stop the loop (when x = 5 or more). The x variable is evaluated after each iteration by the x++ code, which is the same as x = x+1. The x variable is also used to select which slot in the array (arr[x]) is used in order to call the integers saved in the array. Does that help at all?? I would also put the cout command within the for loop so you can see the result of each iteration. Like so: for (int x = 0; x < 5; x++) { sum += arr[x]; cout << sum << endl; }
14th Aug 2016, 10:33 AM
Jason Zeleny
Jason Zeleny - avatar