
Let’s think it through · Start with a story
A girl adds up the pages she read over three days: 2, 3, and 4. The robot has to remember the running total from the previous day.
Break down the process
- Starttotal = 0
- Day one0 + 2 = 2
- Day two2 + 3 = 5
- Day three5 + 4 = 9
An accumulator carries the result from one iteration into the next.
Initializing total outside the loop is like preparing one tally sheet to keep using. Each update builds on the result already there.
01Why does the loop variable keep changing?
for (int i = 1; i <= 3; i++) {
std::cout << i << '\n';
}
i = 1
i = 2
i = 3
The i++ after each iteration changes the value of the same loop-control variable.
02Does the loop make three copies of i?
No. In this example, the program does not create three copies of i in advance. The loop’s control flow repeatedly uses and changes the same object.
03How does a variable outside the loop accumulate a result?
int sum = 0;
for (int i = 1; i <= 3; i++) {
sum = sum + i;
}
sum = 0
sum = 1
sum = 3
sum = 6
04What happens when a variable is declared inside the loop body?
for (int i = 0; i < 3; i++) {
int x = i * 10;
std::cout << x;
}
The scope of x is limited to the braces of the loop body. A new x object’s lifetime begins each time execution enters this block; its lifetime ends when that iteration leaves the block.
05Can you still use i after the loop?
for (int i = 0; i < 3; i++) {
// ...
}
std::cout << i; // error
Here, i is declared in the for initializer. Its scope belongs to the entire for statement, so the name is no longer available after the loop.
06How can you track several variables?
You can draw a small table:
| Iteration | i | sum |
|---|---|---|
| Start | 1 | 0 |
| After iteration 1 | 2 | 1 |
| After iteration 2 | 3 | 3 |
| After iteration 3 | 4 | 6 |
This is one of the most effective ways to understand a loop.
What you have learned
- A loop does not make many copies of a variable in advance.
- A loop-control variable changes according to its update rule.
- A variable outside the loop can preserve an accumulated result across iterations.
- Variables inside the loop body have their own scope and lifetime.
- Tracking variables in a table is an important way to understand loops.
Next: Can We Put a Loop Inside Another Loop?
Your turn
If you set total = 0 at the start of every iteration, then add that day’s pages, will the final result still be 9?
Have an answer? Click to see the explanation
No. Only the last day’s 4 would remain. To add all three days, reset the total only at the beginning.