Control Flow Patterns
While Counter
A while loop repeats as long as its condition stays true.
loop condition
A loop condition is checked before each repetition.
While Counter
while_counter.pl
Replay: real traced execution (multi-file project)
use strict;
use warnings;
my $limit = 3;
my $count = 0;
my $total = 0;
while ($count < $limit) {
$count = $count + 1;
$total = $total + $count;
}
print "limit=$limit\n";
print "count=$count\n";
print "total=$total\n";
use strict;
use warnings;
my $limit = 1;
my $count = 0;
my $total = 0;
while ($count < $limit) {
$count = $count + 1;
$total = $total + $count;
}
print "limit=$limit\n";
print "count=$count\n";
print "total=$total\n";
use strict;
use warnings;
my $limit = 4;
my $count = 0;
my $total = 0;
while ($count < $limit) {
$count = $count + 1;
$total = $total + $count;
}
print "limit=$limit\n";
print "count=$count\n";
print "total=$total\n";
$limit ← 3, $count ← 0, $total ← 0
4my $limit→ 3 = 3; #@limit=1, 45my $count→ 0 = 0;6my $total→ 0 = 0;$count ← 1, $total ← 1
pass 1 of 38while ($count0 < $limit3) {9 $count→ 1 = $count + 1;10 $total→ 1 = $total + $count1;11}All 3 passes — pass 1 is the card above pass $count$total1 0 → 1 0 → 1 2 1 → 2 1 → 3 3 2 → 3 3 → 6 print "limit=$limit ";
13print "limit=$limit3\n";14print "count=$count3\n";15print "total=$total6\n";outputlimit=3 count=3 total=6
$limit ← 1, $count ← 0, $total ← 0
4my $limit→ 1 = 1;5my $count→ 0 = 0;6my $total→ 0 = 0;$count ← 1, $total ← 1
8while ($count0 < $limit1) {9 $count→ 1 = $count + 1;10 $total→ 1 = $total + $count1;11}print "limit=$limit ";
13print "limit=$limit1\n";14print "count=$count1\n";15print "total=$total1\n";outputlimit=1 count=1 total=1
$limit ← 4, $count ← 0, $total ← 0
4my $limit→ 4 = 4;5my $count→ 0 = 0;6my $total→ 0 = 0;$count ← 1, $total ← 1
pass 1 of 48while ($count0 < $limit4) {9 $count→ 1 = $count + 1;10 $total→ 1 = $total + $count1;11}All 4 passes — pass 1 is the card above pass $count$total1 0 → 1 0 → 1 2 1 → 2 1 → 3 3 2 → 3 3 → 6 4 3 → 4 6 → 10 print "limit=$limit ";
13print "limit=$limit4\n";14print "count=$count4\n";15print "total=$total10\n";outputlimit=4 count=4 total=10
Count Up to the Limit
$limitstarts at3.$countand$totalstart at0.- The loop runs while
$count < $limit. - Each pass increases
$count, then adds it to$total. - The final total is
6. | Count after pass | Running total | | --- | --- | |1|1| |2|3| |3|6|
Exercise: while_counter.pl
Use a while loop to count up to a limit and print count and total