Computer science: the while loop

Tutoring computer science, a tenet you need to impart is the use of loops to accomplish repetitive tasks.  The tutor introduces the while loop.

Every programming language I know of has a “while” loop.  A while loop begins by checking a condition.  Finding the condition true, it executes one or more instuctions in the “loop body”.  Finding the condition false, it skips over the loop body, not to return.

Here’s an example of a Perl while loop:

#!/usr/bin/perl
$i=0;
while($ARGV[$i]){
$i++;
}
print “There are $i command line arguments given.”;

The above program counts the inputs given with the function call on the command line. For example: suppose you save the program above as argcount.txt, then run it from the command line like so:

perl argcount.txt Hello, how are you?

You’ll receive the feedback

There are 4 inputs given.

Hence the “while loop” construct: while a condition is met, the loop continues. When the condition fails to be true, the program exits the loop. This program checks for inputs. While it keeps finding them, it repeats the “while” loop. Failing to find any more, it exits the loop.

Notice that, to check for a variable’s existence, Perl lets you use the minimal
while($variable). (I first mentioned this subtlety in my Oct 2 post.) Other programming languages can be more demanding, insisting on while($variable!=null) or something similar. In my (somewhat limited) experience, Perl is the least demanding programming language.

We’ll look more at Perl – as well as at a few of those “more demanding” programming languages – in future posts:)

Source:

Robert’s Perl tutorial

Jack of Oracle Tutoring by Jack and Diane, Campbell River, BC.

Leave a Reply