Foundations
Loops
Loops repeat a block of code for each value in a range.
for loop
A `for` loop can visit each number in a range like `1..$limit`.
Loops
loops.pl
Replay: real traced execution (multi-file project)
use strict;
use warnings;
my $limit = 4;
my $total = 0;
for my $number (1..$limit) {
$total += $number;
}
print "limit=$limit\n";
print "total=$total\n";
use strict;
use warnings;
my $limit = 2;
my $total = 0;
for my $number (1..$limit) {
$total += $number;
}
print "limit=$limit\n";
print "total=$total\n";
use strict;
use warnings;
my $limit = 6;
my $total = 0;
for my $number (1..$limit) {
$total += $number;
}
print "limit=$limit\n";
print "total=$total\n";
$limit ← 4, $total ← 0
4my $limit→ 4 = 4; #@limit=2, 65my $total→ 0 = 0;$total ← 1
pass 1 of 47for my $number1 (1..$limit4) {8 $total→ 1 += $number1;9}All 4 passes — pass 1 is the card above pass $number$total1 1 0 → 1 2 2 1 → 3 3 3 3 → 6 4 4 6 → 10 print "limit=$limit ";
11print "limit=$limit4\n";12print "total=$total10\n";outputlimit=4 total=10
$limit ← 2, $total ← 0
4my $limit→ 2 = 2;5my $total→ 0 = 0;$total ← 1
pass 1 of 27for my $number1 (1..$limit2) {8 $total→ 1 += $number1;9}$total ← 3
pass 2 of 27for my $number2 (1..$limit2) {8 $total→ 3 += $number2;9}print "limit=$limit ";
11print "limit=$limit2\n";12print "total=$total3\n";outputlimit=2 total=3
$limit ← 6, $total ← 0
4my $limit→ 6 = 6;5my $total→ 0 = 0;$total ← 1
pass 1 of 67for my $number1 (1..$limit6) {8 $total→ 1 += $number1;9}All 6 passes — pass 1 is the card above pass $number$total1 1 0 → 1 2 2 1 → 3 3 3 3 → 6 4 4 6 → 10 5 5 10 → 15 6 6 15 → 21 print "limit=$limit ";
11print "limit=$limit6\n";12print "total=$total21\n";outputlimit=6 total=21
What Happens
$limitstarts at4.$totalstarts at0.- The loop visits
1,2,3, and4. - Each number is added to
$total. - The program prints
limit=4andtotal=10.
Loop Picture
| limit | numbers added | total | | --- | --- | --- | | 2 | 1, 2 | 3 | | 4 | 1, 2, 3, 4 | 10 | | 6 | 1, 2, 3, 4, 5, 6 | 21 |
Try It
Exercise: loops.pl
Reproduce total=10 for limit 4, then use the pinned limits 2 and 6 to predict each total.