1.4.2 The for Loop

Another program that produces the output given in the beginning of the section is given below. Here, we use a for loop instead of a while loop to achieve the same purpose.

Program 1.5

#!/usr/bin/perl
#file fahrenheit1.pl

#print Fahrenheit-Celsius table for 0, 20, ..., 300 degrees Fahrenheit

use strict 'vars'; 
my $fahrenheit;
my $celsius;

              #loop through the Fahrenheit values
for ($fahrenheit = 0; $fahrenheit <= 300; $fahrenheit = $fahrenheit+20){
    $celsius = 5/9 * ($fahrenheit - 32);
    printf "%4.0f %6.1f\n", $fahrenheit, $celsius;
}

Here, we do not have the variable initializations that we had in the previous program prior to getting inside the loop.

The for statement has two parts to it. The first part is enclosed inside ( and ). The first part has three expressions in it, each expression separated from the following using the semicolon: ;. An expression is usually not a complete statement, but is a component of a statement. A statement is like a sentence in a natural language like English, and an expression is like a phrase. The first expression gives us the initial value for a variable that is used for controlling the number of iterations of the loop. The second expression gives us the condition that must be satisfied for the block of expressions inside the loop to be executed. Here, the loop is entered only if the value of $fahrenheit is less than or equal to 300. The last expression inside the parentheses tells Perl how the control variable $fahrenheit is modified after every iteration through the loop. The value of $fahrenheit is incremented by 20 in each iteration. Since the value of $fahrenheit starts at 0 in the first iteration and is incremented by 20 in each iteration, eventually the value of $fahrenheit crosses the upper limit of 300 and the execution of the program halts.

The second part of the for statement is included inside { and } and is a block. It contains one or more statements to be executed in each iteration through the for loop.

As a final note, it is not possible to claim that a while loop is better than or worse than a for loop. The choice depends on the programmer and the context of usage. Usually if there is only one initialization and one update expression, for is more convenient and compact than while.