+ 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.*/
4 odpowiedzi
+ 7
it does arr[0]+arr[2]
+ 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
+ 2
sum=sum+arr[0]
sum=0+5
then
sum=5+arr[2]
sum=5+1
+ 1
to do sum all array make
for(int i=0;i<3;i++)
{
sum+=arr[i];
}
now sum =9