+ 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?
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.
0
gotcha thanks!