For Loop
In this lesson, let's understand the concepts and implementation of for loops and nested for loops in Perl.
We'll cover the following
What is a for
loop?
It’s like a while loop, but the initialization and the increment or decrement statements are included within the syntax.
Syntax
A for
loop is set up like this:
Explanation
- Initialization - Initialize the variable that will be used as the loop control variable.
- Condition - The body of the loop only executes when the condition is “true”.
- Increment/Decrement - How the variable changes every time the loop runs.
Example
Here’s an example of how the for
loop works:
for ($i = 0; $i < 10; $i++){print "value of i is: $i\n";}
Explanation
Let’s take a look at the illustration below to understand the code above more clearly.
What does the above for
loop do?
-
Prior to the first iteration, it sets the value of
i
to “0”. -
Next, it tests (like a
while
loop) ifi
is less than “10”. -
If the above condition is true, the body of the loop is run and the program will print the value stored in the variable
i
. -
Next, the terminal cursor moves down to the next line.
-
After the one iteration of the loop is finished,
i
is incremented (by “1”), as specified in the update statement, and the condition is tested again.
So, this loop will run a total of 10 times, printing the value of variable i
each time.
The variable used in
for
loops is generally an integer variable namedi
,j
, ork
.
The loop in the above example can also be written as:
$i=0;for (; $i < 10; $i++){ #initialization can also be done outside loopprint "value of i is: $i\n";}
Similarly, another method to write it is as follows:
$i=0;for (; $i < 10;){ #initialization can also be done outside loop. Note the semicolon is compulsoryprint "value of i is: $i \n";$i++; #the increment of loop control variable can also be done separately}
Nested for
loops
It is possible to nest for
loops. Nesting means including one for
loop in another for
loop.
The syntax for nested for
loops is as follows:
for (initialization ; testing ; updating ) {for (initialization ; testing ; updating) {//body}//body}
Example
Let’s take a look at an example code to understand nesting of for
loops better.
$input = 5;print "How many missiles will you fire?\n";print "I will fire: $input missiles\n";for ($i = 0; $i < $input; $i++) { # outer for loopfor ($j = 3; $j > 0; $j--) { # inner for loopprint "$j ";}$temp = $i+1;print "Missile $temp has launched.\n";}print "All missiles have been launched.\n";
Explanation
For a single value of the variable i
in the outer loop, the inner for loop will iterate over all its values. In this example, the inner loop will iterate over the variable j
from 3 to 1. The variable i
will be incremented, and the outer loop will be repeated, resulting in complete execution of the inner loop again.
Let’s look at the illustration below, which will help us visualize and understand this concept more clearly.