DRAFT
Observed
Lifetime of variables declared in a loop body extends across all loop iterations
Lifetime of variables declared in a loop body is limited to one loop iteration
The lifetime of a variable declared in a loop corresponds to one iteration only, not to all iterations of the loop.
for (int element : array) {
int sum = 0; // sum gets freshly initialized in each iteration
sum += element; // here sum == 0, and we just add the current element
// here sum == element, always
}
// here sum doesn't exist anymore
Students with this misconception may declare an accumulator variable inside the loop body, like this:
for (int element : array) {
int sum = 0;
sum += element;
}
They might believe that sum
gets initialized to 0
in the first iteration,
that in subsequent iterations sum
just gets incremented,
and that after the loop, sum
contains the accumulated total.