Reputation: 69
EXERCISE 1.12: What does the following "for" loop do? what is the final value of sum?
The code that applies to the above exercise is:
#include < iostream >
int main()
{
int sum = 0;
for (int i = -100; i <= 100; ++i)
sum += i;
std::cout << "sum of i is : " << sum << std::endl;
}
The result of sum
or i
is 0
.
My question is with the condition of i <= 100
. how is the answer 0
?
I would think the program would count from -100
all the way up to 100
.
Upvotes: 0
Views: 221
Reputation: 2988
for(<init> ; <test>; <update>) { X;Y;Z; }
loosely translates to
<init>; while (<test>) { X;Y;Z; <update>; }
We use for loops instead of while loops because its often nice to have all the looping logic in one chunk, then all the per-loop doing logic within the braces, where as a while loop can make them a little tougher to separate cognitively.
Upvotes: 0
Reputation: 46415
Indeed it counts all the way from -100
to 100
inclusive. Let's make a shorter example (-2 to <=2):
sum = -2 + -1 + 0 + 1 + 2 = 0
do you see it now?
Upvotes: 4
Reputation: 12675
It adds all of the numbers from -100 to 100. Since 100-100+99-99+...1-1+0=0, the total is 0.
Upvotes: 1