+ 2

C++ for loop+break question

int sum=0; for (int i=1; i<10; i+=2) { if (10/i==2) break; sum+=i; } cout <<sum; why is it 4?

18th Nov 2016, 9:45 PM
maksat osmonov
maksat osmonov - avatar
2 Answers
+ 1
sum starts at 0 (sum = 0) i starts at 1 (int i = 1) The if statement is false, so we do sum += i (take the value of sum + i and assign the result back into sum) so 0 + 1 = 1 Add 2 to the value of i so it is now at 3. Same as before, now sum is 1 and i is 3 so 1 + 3 = 4 Increase the value of i by 2 again, so now it is 5 The if statement is now true, so you break out of the loop.
18th Nov 2016, 9:50 PM
scott johnson
scott johnson - avatar
0
gotcha thanks!
19th Nov 2016, 8:11 PM
maksat osmonov
maksat osmonov - avatar