A while loop repeats as long as its condition stays true.

loop condition A loop condition is checked before each repetition.

While Counter

limit
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";
  1. $limit ← 3, $count ← 0, $total ← 0

    4my $limit→ 3 = 3; #@limit=1, 45my $count→ 0 = 0;6my $total→ 0 = 0;
  2. $count ← 1, $total ← 1

    pass 1 of 3
    8while ($count0 < $limit3) {9    $count→ 1 = $count + 1;10    $total→ 1 = $total + $count1;11}
    All 3 passes — pass 1 is the card above
    pass$count$total
    10 10 1
    21 21 3
    32 33 6
  3. print "limit=$limit ";

    13print "limit=$limit3\n";14print "count=$count3\n";15print "total=$total6\n";
    outputlimit=3
    count=3
    total=6
  1. $limit ← 1, $count ← 0, $total ← 0

    4my $limit→ 1 = 1;5my $count→ 0 = 0;6my $total→ 0 = 0;
  2. $count ← 1, $total ← 1

    8while ($count0 < $limit1) {9    $count→ 1 = $count + 1;10    $total→ 1 = $total + $count1;11}
  3. print "limit=$limit ";

    13print "limit=$limit1\n";14print "count=$count1\n";15print "total=$total1\n";
    outputlimit=1
    count=1
    total=1
  1. $limit ← 4, $count ← 0, $total ← 0

    4my $limit→ 4 = 4;5my $count→ 0 = 0;6my $total→ 0 = 0;
  2. $count ← 1, $total ← 1

    pass 1 of 4
    8while ($count0 < $limit4) {9    $count→ 1 = $count + 1;10    $total→ 1 = $total + $count1;11}
    All 4 passes — pass 1 is the card above
    pass$count$total
    10 10 1
    21 21 3
    32 33 6
    43 46 10
  3. 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

  1. $limit starts at 3.
  2. $count and $total start at 0.
  3. The loop runs while $count < $limit.
  4. Each pass increases $count, then adds it to $total.
  5. 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