Arrays and Iteration
Array Sum (Linear Scan)
Walk an array once, accumulating each element into a running total. This is
the canonical single-pass linear scan and the simplest possible loop
invariant: after step i, total equals the sum of arr[0..i].
Algorithm
Trace Output
basic.pl
use strict; use warnings;
my @arr = (3, 1, 4, 1, 5, 9, 2, 6);
my $total = 0;
my $i = 0;
while ($i < scalar @arr) {
$total = $total + $arr[$i];
$i = $i + 1;
}
print "$total\n";
trace.pl
use strict; use warnings;
my @arr = (3, 1, 4, 1, 5, 9, 2, 6);
my $total = 0;
my $i = 0;
while ($i < scalar @arr) {
my $before = $total;
$total = $total + $arr[$i];
printf("step %d: arr(%d)=%d total %d -> %d\n", $i, $i, $arr[$i], $before, $total);
$i = $i + 1;
}
printf("final total = %d\n", $total);
Complexity
- Time: O(n)
- Space: O(1)
Implementation notes
- Perl: use the explicit
while ($i < scalar @arr)loop with$total = 0and a manual 0-based index. The stdlib does not ship a one-call sum for arrays —List::Util::sumwould hide the loop the lesson is teaching and would also require a CPAN-styleuse. my @arr = (3, 1, 4, 1, 5, 9, 2, 6);documents the fixed-content array; the manual$i = $i + 1step keeps the iteration without leaning onforeach my $val (@arr)that hides the running index.use strict; use warnings;at the top keeps the lesson on the typo-safe path; every$total/$i/@arrreference ismy-declared.- The replay shows
i,arr[i], andtotalbefore and after each addition, matching the lesson spec's state-transition table.
linear scan
Visit each element exactly once in index order.
running total
`total` accumulates the sum as the loop advances.