+ 3

can somebody tells me why this results in 6?

int arr[3]={5,3,1}; int sum=0; for (int i=0; i<3; i+=2){ sum+=arr[i]; } cout<<sum; /* I can't figure out the logic here. In the end of the for loop we get the value of i or in the beggining? I am lost in the relation between sum and for loop. Please for any explanation.*/

20th Dec 2016, 7:39 PM
rubory
rubory - avatar
4 Antworten
+ 7
it does arr[0]+arr[2]
20th Dec 2016, 8:10 PM
Valen.H. ~
Valen.H. ~ - avatar
+ 5
for loop runs for i=0 and i=2 So, sum =0 + 5; //5 for i = 0 sum= 5 +1; //6 for i = 2
20th Dec 2016, 8:51 PM
Caffeinated Gamer YT
Caffeinated Gamer YT - avatar
+ 2
sum=sum+arr[0] sum=0+5 then sum=5+arr[2] sum=5+1
9th Feb 2017, 10:38 PM
Assem
Assem - avatar
+ 1
to do sum all array make for(int i=0;i<3;i++) { sum+=arr[i]; } now sum =9
9th Feb 2017, 10:47 PM
Assem
Assem - avatar