1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
|
#include <iostream>
int main() {
int i = 100;
int sum = 0;
for (int i = 0; i != 10; ++i) {
sum += i;
}
std::cout << i << " " << sum << std::endl;
return 0;
}
|
Line 5: Instatiating an integer
i
, initialized to 100.
Line 6: Instatiating an integer
sum
, initialized to 0.
Line 8: For loop - This integer
i
is different from the integer
i
instantiated on
line 5. Unless you explicitly specify the use of the "more global" integer
i
, any usage of
i
within the scope of the for loop will apply to the integer instantiated on this line since it has more localized scope.
Line 9: With each iteration of the loop, the local integer
i
increases by 1. As this happens, the sum accumulates each of these values. Here are the values of
sum
for each iteration of the for loop:
0
1
3
6
10
15
21
28
36
45 |
When the for loop ends,
sum
will have a value of 45.
Line 12: First, you print integer
i
instantiated on
line 5. This variable hasn't been changed, so it's value still is 100. Then, you print a space (" ") followed by
sum
.